package com.jhhc.StormSurgeForecast.StormSurge.Uitl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONReader;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jhhc.FloodForecast.Sensor.Pojo.BDMS_ST_SENSORALARM_B;
import com.jhhc.FloodForecast.Sensor.Pojo.BDMS_ST_SENSOR_B;
import com.jhhc.FloodForecast.Sensor.Pojo.BDMS_ST_STBPRP_B;
import com.jhhc.FloodForecast.Sensor.Service.BDMS_ST_SENSORALARM_BService;
import com.jhhc.FloodForecast.Sensor.Service.BDMS_ST_SENSOR_BService;
import com.jhhc.FloodForecast.Sensor.Service.BDMS_ST_STBPRP_BService;
import com.jhhc.RHDB.Data.Pojo.Data;
import com.jhhc.RHDB.Data.Pojo.ST_TIDE_R;
import com.jhhc.RHDB.Data.Service.ST_TIDE_RService;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Pojo.*;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Pojo.ChartEntity.ChartData;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Service.*;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Util.GetInformTxtUtil;
import com.jhhc.StormSurgeForecast.StormSurge.Pojo.*;
import com.jhhc.StormSurgeForecast.StormSurge.Pojo.Dto.DownloadImages;
import com.jhhc.StormSurgeForecast.StormSurge.Pojo.Dto.UpdateTideData;
import com.jhhc.StormSurgeForecast.StormSurge.Pojo.FBC.*;
import com.jhhc.StormSurgeForecast.StormSurge.Pojo.Param.GridParam;
import com.jhhc.StormSurgeForecast.StormSurge.Pojo.Product.*;
import com.jhhc.StormSurgeForecast.StormSurge.Service.*;
import com.jhhc.Weathers.Picture.Pojo.Datas;
import com.jhhc.utils.GetDocPdfContentUtil;
import com.jhhc.utils.ImageBase64;
import com.jhhc.utils.JsonResult;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

import io.lettuce.core.ScriptOutputType;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.web.client.RestTemplate;
import org.apache.poi.xwpf.usermodel.XWPFPicture;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;


import static org.apache.commons.lang3.StringUtils.isWhitespace;
import static org.apache.commons.lang3.StringUtils.remove;

@Service
@Transactional
public class GetTyphoonUitl {

    @Autowired
    private BDMS_FBC_RESULT_SCHEMEService bdms_fbc_result_schemeService;
    @Autowired
    private BDMS_FBC_RESULTService bdms_fbc_resultService;
    @Autowired
    private ST_TIDE_RService st_tide_rService;
    @Autowired
    private GetDataUtil getDataUtil;
    @Autowired
    private BDMS_ST_ASTROTD_FService bdms_st_astrotd_fService;
    @Autowired
    private BDMS_ST_STBPRP_BService bdms_st_stbprp_bService;
    @Autowired
    private BDMS_FBC_RESULT_AService bdms_fbc_result_aService;
    @Autowired
    private BDMS_FBC_ASTROTD_AService bdms_fbc_astrotd_aService;
    @Autowired
    private BDMS_ST_SENSORALARM_BService bdms_st_sensoralarm_bService;
    @Autowired
    private BDMS_FBC_OCEANMODEL_BService bdms_fbc_oceanmodel_bService;
    @Autowired
    private BDMS_CALCULATESCHEME_MService bdms_calculatescheme_mService;
    @Autowired
    private BDMS_FBC_RESULT_PService bdms_fbc_result_pService;
    @Autowired
    private ArithmeticUtil arithmeticUtil;
    @Autowired
    private BDMS_FBC_TFService bdms_fbc_tfService;
    @Autowired
    private BDMS_FBC_TFINFO_BService bdms_fbc_tfinfo_bService;
    @Autowired
    private GetDocPdfContentUtil getDocPdfContentUtil;
    @Autowired
    private GetInformTxtUtil getInformTxtUtil;

    @Autowired
    private BDMS_ST_SENSOR_BService bdms_st_sensor_bService;

    @Autowired
    private BDMS_FBC_SEAWALL_PService bdms_fbc_seawall_pService;
    @Autowired
    private BDMS_PRODUCT_INFOService bdms_product_infoService;
    @Autowired
    private BDMS_PRODUCT_PROJ_LINKService bdms_product_proj_linkService;
    @Autowired
    private BDMS_PRODUCT_RESULTService bdms_product_resultService;
    @Autowired
    private BDMS_FBC_SEAWALL_BService bdms_fbc_seawall_bService;
    @Autowired
    private BDMS_FBC_TFPATH_RService bdms_fbc_tfpath_rService;
    @Autowired
    private BDMS_FBC_TFPATH_FService bdms_fbc_tfpath_fService;
    @Autowired
    private JfreeChartUtils jfreeChartUtils;
    @Value("${serverType}")
    String serverType;

    //分割字符
    List<Double> values;
    String data_all;

    DecimalFormat  df = new DecimalFormat("0.00");
    DecimalFormat  decimalFormat = new DecimalFormat("######");
    DecimalFormat a1 = new DecimalFormat("000000");
    DecimalFormat a2 = new DecimalFormat("#00000");
    Calendar calendar = new GregorianCalendar();
    public void DATA_All(String value) {
        if (values == null) {
            values = new ArrayList<>();
        } else {
            values.clear();
        }
        this.data_all = value;
        if (value == null) {
            return;
        }
        int version = 1;
        int pointIndex = value.indexOf(".");
        if (pointIndex > 0 && value.startsWith("v")) {
            version = Integer.parseInt(value.substring(1, pointIndex - 1));
        }
        if (version == 1) {
            int valueItemLength;
            //System.out.println("value.length():"+value.length());
            for (int i = 0; i < value.length(); i += valueItemLength) {
                // System.out.println("value.charAt(i):"+value.charAt(i));
                valueItemLength = value.charAt(i) == '-' ? 4 : 3;
                if (valueItemLength + i > value.length()) {
                    //System.out.println("tiaochu");
                    continue;
                } else {
                    if (!value.substring(i, valueItemLength + i).isEmpty()) {
                        //  System.out.println(i);
                        //   String str=value.substring(i, valueItemLength+i);
                        //    System.out.println("value.substring(i, valueItemLength)"+str);
                        double var = Double.parseDouble(value.substring(i, valueItemLength + i));
                        // System.out.println("var:"+var);
                        values.add(var / 100);
                    }

                }
            }
        } else if (version == 2) {
            String datavalue = value.substring(pointIndex + 1);
            String[] data0 = datavalue.split(String.valueOf("+"));
            for (int i = 0; i < data0.length; i++) {
                if (isWhitespace(data0[i])) {
                    continue;
                }
                String[] data1 = data0[i].split(String.valueOf("+"));
                for (int j = 0; j < data1.length; j++) {
                    if (isWhitespace(data1[j])) {
                        continue;
                    }
                    if (j == 0) {
                        values.add(Double.parseDouble(data1[0]));
                    } else {
                        values.add(Double.parseDouble(data1[j]) * -1);
                    }
                }
            }
        }
    }

    public void data_all(String value) {
        if (values == null) {
            values = new ArrayList<>();
        } else {
            values.clear();
        }
        this.data_all = value;
        if (value == null) {
            return;
        }
        int version = 1;
        int pointIndex = value.indexOf(".");
        if (pointIndex > 0 && value.startsWith("v")) {
            version = Integer.parseInt(value.substring(1, pointIndex - 1));
        }
        if (version == 1) {
            int valueItemLength;
            //System.out.println("value.length():"+value.length());
            for (int i = 0; i < value.length(); i += valueItemLength) {
                // System.out.println("value.charAt(i):"+value.charAt(i));
                valueItemLength = value.charAt(i) == '-' ? 6 : 6;
                if (valueItemLength + i > value.length()) {
                    //System.out.println("tiaochu");
                    continue;
                } else {
                    if (!value.substring(i, valueItemLength + i).isEmpty()) {
                        //    System.out.println(i);
                        //  String str=value.substring(i, valueItemLength+i);
                        //    System.out.println("value.substring(i, valueItemLength)"+str);
                        double var = Double.parseDouble(value.substring(i, valueItemLength + i));
                        // System.out.println("var:"+var);
                        values.add(var / 100);
                    }

                }
            }
        } else if (version == 2) {
            String datavalue = value.substring(pointIndex + 1);
            String[] data0 = datavalue.split(String.valueOf("+"));
            for (int i = 0; i < data0.length; i++) {
                if (isWhitespace(data0[i])) {
                    continue;
                }
                String[] data1 = data0[i].split(String.valueOf("+"));
                for (int j = 0; j < data1.length; j++) {
                    if (isWhitespace(data1[j])) {
                        continue;
                    }
                    if (j == 0) {
                        values.add(Double.parseDouble(data1[0]));
                    } else {
                        values.add(Double.parseDouble(data1[j]) * -1);
                    }
                }
            }
        }
    }

    //获取预报方案
    public List<BDMS_FBC_RESULT_SCHEME> getBdms_fbc_result_scheme(int projectId,
                                                                  Integer typhoonId, String starTime, String endTime, Integer modelId, Boolean isPublished) {
        List<BDMS_FBC_RESULT_SCHEME> bdms_fbc_result_schemeList = new ArrayList<>();
        if (typhoonId != null && isPublished) {
            //FLAG=1
            bdms_fbc_result_schemeList = bdms_fbc_result_schemeService.GetCalSchemeInfoByTyphoonIds(projectId, typhoonId, starTime, endTime, modelId);
        } else if (typhoonId != null) {
            //WU FLAG
            bdms_fbc_result_schemeList = bdms_fbc_result_schemeService.GetCalSchemeInfoByTyphoonIds2(projectId, typhoonId, starTime, endTime, modelId);
        } else if (isPublished) {
            bdms_fbc_result_schemeList = bdms_fbc_result_schemeService.GetCalSchemeInfoByPidTrue(projectId, starTime, endTime, modelId);
        } else {
            bdms_fbc_result_schemeList = bdms_fbc_result_schemeService.GetCalSchemeInfoByPidFalse(projectId, starTime, endTime, modelId);
        }
        return bdms_fbc_result_schemeList;
    }


    //获取预报结果
    public List<CalResult> getBdms_fbc_result(int pid, String calSchemeId, List<String> stationCodes, int TwcDept, int backDays, Integer DBType, Integer stepLength) {
        //构造日期函数
        // 日期格式转换
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = new GregorianCalendar();
        //构造返回对象
        List<CalResult> calResults = new ArrayList<>();
        //查询结果
        //增水数据
        //获取取数码
        List<PointResult> pointResultsList = new ArrayList<>();
        List<String> Stcds = new ArrayList<>();
        List<BDMS_ST_SENSOR_B> bdms_st_sensor_bs = bdms_st_sensor_bService.selectByStcds(stationCodes);
        for (BDMS_ST_SENSOR_B bdms_st_sensor_b : bdms_st_sensor_bs) {
            Stcds.add(bdms_st_sensor_b.getDatacode());

        }
        if (DBType == 1) {  //老表结构
            List<BDMS_FBC_RESULT> bdms_fbc_results = bdms_fbc_resultService.selecTBySchemeId(Integer.parseInt(calSchemeId), stationCodes);
            String StartTime = null;
            String EndTime = null;
            //预报增水
            String startTime = null;
            //查询预报增水值
            //获取预报方案
            Integer typhoonId = null;
            String Forecasttime = null;

            //查询台风表
            List<BDMS_FBC_RESULT_SCHEME> bdms_fbc_result_schemes = bdms_fbc_result_schemeService.selectByPid(pid, Integer.parseInt(calSchemeId));
            BDMS_FBC_TF bdmsFbcTf = bdms_fbc_tfService.queryById(String.valueOf(bdms_fbc_result_schemes.get(0).getTfid()));
            for (BDMS_FBC_RESULT_SCHEME bdms_fbc_result_scheme : bdms_fbc_result_schemes) {
                StartTime = bdms_fbc_result_scheme.getYmdhm();
                startTime = bdms_fbc_result_scheme.getYmdhm();
                String endtm = bdms_fbc_result_scheme.getYmdhm();
                typhoonId = bdms_fbc_result_scheme.getTfid();
                Forecasttime = bdms_fbc_result_scheme.getYmdhm();
                int day;
                Date end;
                try {
                    //设置结束时间
                    end = format.parse(endtm);
                    calendar.setTime(end);
                    day = bdms_fbc_result_scheme.getCalnum();
                    calendar.add(Calendar.HOUR, +day);
                    EndTime = format.format(calendar.getTime());
                    //设置天文潮开始结束时间
                    Date date;
                    date = format.parse(startTime);
                    calendar.setTime(date);
                    calendar.add(Calendar.DATE, -backDays);
                    startTime = format.format(calendar.getTime());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //获取到站码集合后，去调用获取实测和天文潮数据
            //获取实测
            List<ST_TIDE_R> st_tide_rList = st_tide_rService.selectByStcd(Stcds, startTime, EndTime);
            String min = "00";
            //两个条件
            //获取天文超数据
            List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFList = bdms_st_astrotd_fService.selectFTDZ(stationCodes, startTime, EndTime, TwcDept);
            //获取高低潮
            //构造比较日期
            String TdzTime;
            String FtdzTime;
            String DataTime;
            //获取到实测和天文潮后构造 PointResult
            //Listdata

            if (bdmsStAstrotdFList.size() > 0) {
                for (String stcd : stationCodes) {
                    List<Data> dataList = new ArrayList<>();
                    List<PointResult> pointResults = new ArrayList<>();
                    List<PointResult> pointHLResults = new ArrayList<>();
                    //构造返回对象
                    CalResult calResult = new CalResult();
                    //设置站码
                    calResult.setStationCode(stcd);
                    calResult.setTyphoonId(typhoonId);
                    calResult.setTyphoonName(bdmsFbcTf.getTfnameC());
                    calResult.setForecastTime(Forecasttime);
                    List<BDMS_FBC_RESULT> bdms_fbc_resultsList = bdms_fbc_results.stream().filter(BDMS_FBC_RESULT -> BDMS_FBC_RESULT.getStcd().equals(stcd)).collect(Collectors.toList());
                    //获取值`xedcrtv fty
                    for (BDMS_FBC_RESULT bdms_fbc_result : bdms_fbc_resultsList) {
                        if (bdms_fbc_result!=null){
                            DATA_All(bdms_fbc_result.getDataAll());
                            //获取values平均值
                            Double avg;
                            if (values != null) {
                                for (int i = 0; i < values.size(); i++) {
                                    try {
                                        Date date = format.parse(StartTime);
                                        calendar.setTime(date);
                                        calendar.add(Calendar.HOUR, +i);
                                        dataList.add(new Data(format.format(calendar.getTime()), values.get(i)));
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                            dataList.sort(Comparator.comparing(Data::getTM));
                        }
                    }
                    //站码  分组
                    String datacode = bdms_st_sensor_bs.stream().filter(BDMS_ST_SENSOR_B -> BDMS_ST_SENSOR_B.getStcd().equals(stcd)).findAny().orElse(null).getDatacode();
                    List<ST_TIDE_R> st_tide_rs = st_tide_rList.stream().filter(ST_TIDE_R -> ST_TIDE_R.getStcd().equals(datacode) && ST_TIDE_R.getMin().equals(min)).collect(Collectors.toList());
                    List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFs = bdmsStAstrotdFList.stream().filter(BDMS_ST_ASTROTD_F -> BDMS_ST_ASTROTD_F.getStcd().equals(stcd)).collect(Collectors.toList());
//                    for (BDMS_ST_ASTROTD_F bdmsStAstrotdF : bdmsStAstrotdFs) {
//                        FtdzTime = bdmsStAstrotdF.getYmdh();
//                        for (Data data : dataList) {
//                            DataTime = data.getTM();
//                            if (bdmsStAstrotdF.getFtdz() != null) {
//                                //设置高低潮
//                                if (bdmsStAstrotdF.getHltdmk() != null && bdmsStAstrotdF.getHltdmk() > 0) {
//                                    //
//                                    PointResult pointHLResult = new PointResult();
//                                    pointHLResult.setTm(bdmsStAstrotdF.getYmdh());
//                                    //System.out.println(pointHLResult.getTm()+"hlp");
//                                    pointHLResult.setTwc(bdmsStAstrotdF.getFtdz());
//                                    pointHLResults.add(pointHLResult);
//                                } else {
//                                    //设置天文潮预报对象
//                                    PointResult pointResult = new PointResult();
//                                    pointResult.setTm(bdmsStAstrotdF.getYmdh());
//                                    pointResult.setTwc(bdmsStAstrotdF.getFtdz());
//                                    String TM = FtdzTime;
//                                    if (st_tide_rs.size() > 0) {
//                                        ST_TIDE_R st_tide_r = st_tide_rs.stream().filter(ST_TIDE_R -> ST_TIDE_R.getTm().equals(TM)).findAny().orElse(null);
//                                        //通过时间获取数据
//                                        if (st_tide_r != null) {
//                                            pointResult.setTdz(st_tide_r.getTdz());
//                                        }
//                                    }
//                                    Data datas = dataList.stream().filter(Data -> Data.getTM().equals(TM)).findAny().orElse(null);
//                                    if (datas != null) {
//                                        if (datas.getTM().equals(FtdzTime)) {
//                                            pointResult.setTm(datas.getTM());
//                                            // System.out.println(pointResult.getTm()+"p");
//                                            pointResult.setZs(datas.getValue());
//                                            double a = pointResult.getZs();
//                                            double b = bdmsStAstrotdF.getFtdz();
//                                            float a1 = (float) a;
//                                            float b1 = (float) b;
//
//
//
//
//                                            pointResult.setFtdz(Double.parseDouble(String.format("%.2f", a1 + b1)));
//                                        }
//                                    }
//                                    //特征值集合
//                                    pointResults.add(pointResult);
//                                    break;
//                                }
//                                break;
//                            }
//                            continue;
//                        }
//                        // break;
//                    }

                    for (int i = 0; i < bdmsStAstrotdFs.size(); i++) {
                        FtdzTime = bdmsStAstrotdFs.get(i).getYmdh();
                        if (dataList.size()>0) {
                            for (int k = 0; k < dataList.size(); k++) {
                                if (bdmsStAstrotdFs.get(i).getFtdz() != null) {
                                    //设置高低潮
                                    if (bdmsStAstrotdFs.get(i).getHltdmk() != null && bdmsStAstrotdFs.get(i).getHltdmk() > 0) {
                                        //
                                        PointResult pointHLResult = new PointResult();
                                        pointHLResult.setTm(bdmsStAstrotdFs.get(i).getYmdh());
                                        pointHLResult.setTwc(bdmsStAstrotdFs.get(i).getFtdz());
                                        pointHLResults.add(pointHLResult);
                                    } else {
                                        //设置天文潮预报对象
                                        PointResult pointResult = new PointResult();
                                        pointResult.setTm(bdmsStAstrotdFs.get(i).getYmdh());
                                        pointResult.setTwc(bdmsStAstrotdFs.get(i).getFtdz());
                                        String TM = FtdzTime;
                                        if (st_tide_rs.size() > 0) {
                                            ST_TIDE_R st_tide_r = st_tide_rs.stream().filter(ST_TIDE_R -> ST_TIDE_R.getTm().equals(TM)).findAny().orElse(null);
                                            //通过时间获取数据
                                            if (st_tide_r != null) {
                                                pointResult.setTdz(st_tide_r.getTdz());
                                            }
                                        }
                                        if (stepLength != null) {
                                            if (i + 1 < bdmsStAstrotdFs.size()) {
                                                String startTM = bdmsStAstrotdFs.get(i).getYmdh();
                                                String endTM = bdmsStAstrotdFs.get(i + 1).getYmdh();
                                                try {
                                                    if (format.parse(startTM).getTime() < format.parse(Forecasttime).getTime()) {
                                                        Double ta = null;
                                                        Double tc = null;
                                                        ta = bdmsStAstrotdFs.get(i).getFtdz();
                                                        tc = bdmsStAstrotdFs.get(i + 1).getFtdz();
                                                        List<PointResult> pointResultsTwcs = arithmeticUtil.getInterpolation(startTM, endTM, ta, tc, stepLength, "twc");
                                                        for (PointResult pointResultsTwc : pointResultsTwcs) {
                                                            PointResult pointResult1 = new PointResult();
                                                            pointResult1.setTm(pointResultsTwc.getTm());
                                                            pointResult1.setTwc(pointResultsTwc.getTwc());
                                                            pointResults.add(pointResult1);
                                                        }
                                                    }
                                                } catch (Exception ignored) {

                                                }


                                            }
                                        }


                                        Data datas = dataList.stream().filter(Data -> Data.getTM().equals(TM)).findAny().orElse(null);
                                        if (datas != null) {
                                            if (datas.getTM().equals(FtdzTime)) {
                                                pointResult.setTm(datas.getTM());
                                                pointResult.setZs(datas.getValue());
                                                double a = pointResult.getZs();
                                                double b = bdmsStAstrotdFs.get(i).getFtdz();
                                                float a1 = (float) a;
                                                float b1 = (float) b;
                                                pointResult.setFtdz(Double.parseDouble(String.format("%.2f", a1 + b1)));


                                                if (stepLength != null) {
                                                    if (i + 1 < bdmsStAstrotdFs.size()) {
                                                        String startTM = bdmsStAstrotdFs.get(i).getYmdh();
                                                        String endTM = bdmsStAstrotdFs.get(i + 1).getYmdh();
                                                        Double ta = null;
                                                        Double tc = null;
                                                        ta = bdmsStAstrotdFs.get(i).getFtdz();
                                                        tc = bdmsStAstrotdFs.get(i + 1).getFtdz();
                                                        List<PointResult> pointResultsTwcs = arithmeticUtil.getInterpolation(startTM, endTM, ta, tc, stepLength, "twc");
                                                        Double za = null;
                                                        Double zc = null;
                                                        if (k + 1 < dataList.size()) {
                                                            za = dataList.get(k).getValue();
                                                            zc = dataList.get(k + 1).getValue();

                                                        }
                                                        List<PointResult> pointResultsZss = arithmeticUtil.getInterpolation(startTM, endTM, za, zc, stepLength, "zs");
                                                        //  pointResults.addAll(pointResultsZs);
                                                        //List<PointResult> pointResultsFtzds = arithmeticUtil.getInterpolation(startTM,endTM,fa,fc,stepLength,"ftdz");
                                                        for (PointResult pointResultsTwc : pointResultsTwcs) {
                                                            for (PointResult pointResultsZs : pointResultsZss) {
                                                                if (pointResultsTwc.getTm().equals(pointResultsZs.getTm())) {
                                                                    PointResult newPointResult = new PointResult();
                                                                    newPointResult.setTm(pointResultsZs.getTm());
                                                                    newPointResult.setZs(pointResultsZs.getZs());
                                                                    newPointResult.setTwc(pointResultsTwc.getTwc());
                                                                    newPointResult.setFtdz(Double.valueOf(String.format("%.2f", newPointResult.getZs() + newPointResult.getTwc())));

                                                                    pointResultsList.add(newPointResult);
                                                                }
                                                            }
                                                        }


                                                    }
                                                }
                                                for (int z = 0; z < pointHLResults.size(); z++) {
                                                    String tm = pointHLResults.get(z).getTm();
                                                    //System.out.println(pointHLResults.get(z));
                                                    try {
                                                        Date sd = format.parse(pointHLResults.get(z).getTm());
                                                        sd.setMinutes(0);
                                                        String stm = format.format(sd);
                                                        calendar.setTime(sd);
                                                        calendar.add(Calendar.HOUR, +1);
                                                        String etm = format.format(calendar.getTime());

                                                        Double za = dataList.stream().filter(data -> data.getTM().equals(stm)).findAny().orElse(null).getValue();
                                                        Double zc = dataList.stream().filter(data -> data.getTM().equals(etm)).findAny().orElse(null).getValue();
                                                        List<PointResult> pointResultsHlZss = arithmeticUtil.getInterpolation(stm, etm, za, zc, 1, "zs");
                                                        PointResult pointResultzs = pointResultsHlZss.stream().filter(PointResult -> PointResult.getTm().equals(tm)).findAny().orElse(null);

                                                        PointResult pointResult1 = new PointResult();
                                                        pointResult1.setTm(pointHLResults.get(z).getTm());
                                                        pointResult1.setZs(pointResultzs.getZs());
                                                        pointResult1.setTwc(pointHLResults.get(z).getTwc());
                                                        pointResult1.setFtdz(Double.valueOf(String.format("%.2f", pointResult1.getZs() + pointResult1.getTwc())));
                                                        pointHLResults.remove(z);
                                                        pointHLResults.add(pointResult1);

                                                    } catch (Exception e) {

                                                    }

                                                }
                                            }
                                        }
                                        //特征值集合
                                        pointResults.add(pointResult);

                                        break;
                                    }
                                    break;
                                }
                                continue;
                            }
                        }else {
                            PointResult pointResult = new PointResult();
                            pointResult.setTm(bdmsStAstrotdFs.get(i).getYmdh());
                            pointResult.setTwc(bdmsStAstrotdFs.get(i).getFtdz());
                            pointResult.setFtdz(bdmsStAstrotdFs.get(i).getFtdz());
                            pointResultsList.add(pointResult);
                        }
                        // break;
                    }


                    pointHLResults.sort(Comparator.comparing(PointResult::getTm));
                    List<PointResult> phl = pointHLResults.stream().distinct().collect(Collectors.toList());
                    pointResults.addAll(phl);
                    pointResults.addAll(pointResultsList);

                    pointResults.sort(Comparator.comparing(PointResult::getTm));

                    //gouzao    PointHLResults 作业预报开始时间 结束之间 范围的数据  List  gouzao
                    //判断
//                    try {
//                        calendar.setTime(format.parse(StartTime));
//                        calendar.add(Calendar.HOUR, -1);
//                        Date start = calendar.getTime();
//                        calendar.setTime(format.parse(EndTime));
//                        calendar.add(Calendar.HOUR, -1);
//                        Date end = calendar.getTime();
//                        List<PointResult> pointResults1 = pointResults.stream().filter(
//                                PointResult -> {
//                                    try {
//                                        return format.parse(PointResult.getTm()).after(start)
//                                                && format.parse(PointResult.getTm()).before(end);
//                                    } catch (ParseException e) {
//                                        e.printStackTrace();
//                                    }
//                                    return false;
//                                }).collect(Collectors.toList());
//                        List<PointResult> pointHLResults1 = pointHLResults.stream().filter(
//                                PointResult -> {
//                                    try {
//                                        return start.before(format.parse(PointResult.getTm())) &&
//                                                start.before(format.parse(PointResult.getTm()));
//                                    } catch (ParseException e) {
//                                        e.printStackTrace();
//                                    }
//                                    return false;
//                                }).collect(Collectors.toList());
//                        //   List<PointResult> pointHLResults2 = new ArrayList<>();
//                        for (int i = 0; i < pointHLResults1.size(); i++) {
//                            PointResult pointHLResult = new PointResult();
//                            String pointHLResultsYear = pointHLResults1.get(i).getTm().substring(0, 16);
//                            boolean res = Integer.parseInt(pointHLResultsYear.substring(14, 16)) >= 30;
//                            String time = pointHLResultsYear.substring(0, 13) + ":00:00.0";
//                            Date Time = format.parse(time);
//                            calendar.setTime(Time);
//                            if (res) {
//                                calendar.add(Calendar.HOUR, +1);
//                            }
//                            String day = format.format(calendar.getTime());
//                            //根据日期去获取对应的逐时
//                            PointResult pointResult = pointResults1.stream().filter(PointResult -> PointResult.getTm().equals(day)).findAny().orElse(null);
//                            if (pointResult != null) {
//                                pointHLResult.setTm(pointHLResults1.get(i).getTm());
//                                String tm = pointHLResult.getTm();
//                                pointHLResult.setZs(pointResult.getZs());
//                                pointHLResult.setTwc(pointHLResults1.get(i).getTwc());
//                                pointHLResult.setFtdz(pointHLResult.getZs() + pointHLResult.getTwc());
//                                for (PointResult pointHLs : pointHLResults) {
//                                    if (pointHLs.getTm().equals(tm)) {
//                                        pointHLs.setTm(tm);
//                                        pointHLs.setTwc(pointHLResult.getTwc());
//                                        pointHLs.setZs(pointHLResult.getZs());
//                                        pointHLs.setFtdz(pointHLs.getZs() + pointHLs.getTwc());
//                                    }
//                                }
//                            }
//                        }
//                        calResult.setPointResults(pointResults);
//                        calResult.setPointHLResults(pointHLResults);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
                    calResult.setPointResults(pointResults.stream().distinct().collect(Collectors.toList()));
                    calResult.setPointHLResults(pointHLResults);
                    try {
                        PointResult poTwc = calResult.getPointResults().stream().max(Comparator.comparing(PointResult::getTwc)).orElse(null);
                        if (poTwc != null) {
                            calResult.setMaxTwcTm(poTwc.getTm());
                            calResult.setMaxTwc(poTwc.getTwc());
                        }

                        List<PointResult> pointResultsZs = calResult.getPointResults().stream().filter(PointResult -> PointResult.getZs() != null).collect(Collectors.toList());
                        PointResult poZs = pointResultsZs.stream().max(Comparator.comparing(PointResult::getZs)).orElse(null);
                        if (poZs != null) {
                            calResult.setMaxZsTm(poZs.getTm());
                            calResult.setMaxZs(poZs.getZs());
                        }
                        List<PointResult> pointResultsFtdz = calResult.getPointResults().stream().filter(PointResult -> PointResult.getFtdz() != null).collect(Collectors.toList());
                        PointResult poFtzd = pointResultsFtdz.stream().max(Comparator.comparing(PointResult::getFtdz)).orElse(null);
                        if (poFtzd != null) {
                            calResult.setMaxFtdzTm(poFtzd.getTm());
                            calResult.setMaxFtdz(poFtzd.getFtdz());
                        }
                    } catch (NullPointerException e) {

                    }
                    calResults.add(calResult);
                }

            }
//        } else if (DBType == 0 || DBType == null) {
//            List<BDMS_FBC_RESULT_P> bdms_fbc_results = bdms_fbc_result_pService.selecTBySchemeId(calSchemeId, stationCodes);
//            List<String> stcds = new ArrayList<>();
//            for (BDMS_FBC_RESULT_P bdms_fbc_result : bdms_fbc_results) {
//                stcds.add(bdms_fbc_result.getPtkey());
//            }
//            String StartTime = null;
//            String EndTime = null;
//            //预报增水
//            String startTime = null;
//            //查询预报增水值
//            //获取预报方案  新表
//            Integer typhoonId = null;
//            String Forecasttime = null;
//
//            //创建集合
//            List<ChartData> chartDatas = new ArrayList<>();
//            //返回对象
//            ChartData zschartData  =new ChartData();
//            zschartData.setValueName("预报增水");
//            zschartData.setCalDataType("zs");
//            zschartData.setOrder(1);
//            zschartData.setUnit("m");
//            ChartData twcchartData  =new ChartData();
//            twcchartData.setValueName("天文潮");
//            twcchartData.setCalDataType("twc");
//            twcchartData.setOrder(2);
//            twcchartData.setUnit("m");
//            ChartData ftdzchartData  =new ChartData();
//            ftdzchartData.setValueName("预报综合潮位");
//            ftdzchartData.setCalDataType("ftdz");
//            ftdzchartData.setOrder(3);
//            ftdzchartData.setUnit("m");
//            ChartData   tdzcartData  =new ChartData();
//            tdzcartData.setValueName("实测潮位");
//            tdzcartData.setCalDataType("tdz");
//            tdzcartData.setOrder(4);
//            tdzcartData.setUnit("m");
//
//
//            List<BDMS_CALCULATESCHEME_M1> bdms_fbc_result_schemes = bdms_calculatescheme_mService.selectShcemeByPidCalID(pid, calSchemeId);
//
//            String param = bdms_fbc_result_schemes.get(0).getParams();
//            String[] params = param.split(",");
//            typhoonId = Integer.valueOf(params[0]);
//
//            Integer projectid =  bdms_fbc_result_schemes.get(0).getPid();
//            String modelid=  bdms_fbc_result_schemes.get(0).getMdid();
//
//            BDMS_FBC_OCEANMODEL_B bdms_fbc_oceanmodel_b = bdms_fbc_oceanmodel_bService.getModelInfoByModelId(projectid,modelid);
//
//            BDMS_FBC_TFINFO_B bdmsFbcTfinfoB = bdms_fbc_tfinfo_bService.queryById(String.valueOf(typhoonId));
//
//            for (BDMS_CALCULATESCHEME_M1 bdms_fbc_result_scheme : bdms_fbc_result_schemes) {
//                StartTime = bdms_fbc_result_scheme.getDtmforecast();
////               String param = bdms_fbc_result_scheme.getParams();
////               String[] params =param.split(",");
////                typhoonId = Integer.valueOf(params[0]);
//                Forecasttime = bdms_fbc_result_scheme.getDtmforecast();
//                try {
//                    calendar.setTime(format.parse(StartTime));
//                    calendar.add(Calendar.DATE, -backDays);
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }
//                startTime = format.format(calendar.getTime());
//                EndTime = bdms_fbc_result_scheme.getDtmend();
//
//            }
//
//            //获取到站码集合后，去调用获取实测和天文潮数据
//            //获取实测
//            List<ST_TIDE_R> st_tide_rList = st_tide_rService.selectByStcd(Stcds, startTime, EndTime);
//            String min = "00";
//            //两个条件
//            //获取天文超数据
//            List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFList = bdms_st_astrotd_fService.selectFTDZ(stationCodes, startTime, EndTime, TwcDept);
//            //获取高低潮
//            //构造比较日期
//            String TdzTime;
//            String FtdzTime;
//            String DataTime;
//            //获取到实测和天文潮后构造 PointResult
//            //Listdata
//            List<Data> dataList = new ArrayList<>();
//
//            if (bdmsStAstrotdFList.size() > 0) {
//                for (String stcd : stationCodes) {
//
//                    BDMS_ST_SENSOR_B bdms_st_sensor_b= bdms_st_sensor_bs.stream().filter(BDMS_ST_SENSOR_B->BDMS_ST_SENSOR_B.getStcd().equals(stcd)).findAny().orElse(null);
//
//                    //过程线
//                    List<Data> zsDatas  =new ArrayList<>();
//                    List<Data> twcDatas =new ArrayList<>();
//                    List<Data> ftdzDatas  =new ArrayList<>();
//                    List<Data> tdzDatas  =new ArrayList<>();
//
//
//                    List<PointResult> pointResults = new ArrayList<>();
//                    List<PointResult> pointHLResults = new ArrayList<>();
//                    //构造返回对象
//                    CalResult calResult = new CalResult();
//                    //设置站码
////                    calResult.setStationCode(stcd);
////                    calResult.setTyphoonId(typhoonId);
////                    calResult.setForcastTime(Forecasttime);
////                    calResult.setTyphoonName(bdmsFbcTfinfoB.getTfnameC());
//
//                    calResult.setMainHeading(bdms_st_sensor_b.getStnm()+"("+stcd+")"+"预报潮位过程图");
//                    calResult.setSubHeading("作业预报时间:"+Forecasttime+" 预报路径:"+params[1]+" 预报模型:"+bdms_fbc_oceanmodel_b.getModelnm()+" 台风系数:"+params[2]);
//                    calResult.setForecastTime(Forecasttime);
//                    List<BDMS_FBC_RESULT_P> bdms_fbc_resultsList = bdms_fbc_results.stream().filter(BDMS_FBC_RESULT -> BDMS_FBC_RESULT.getPtkey().equals(stcd)).collect(Collectors.toList());
//                    //获取值
//                    for (BDMS_FBC_RESULT_P bdms_fbc_result : bdms_fbc_resultsList) {
//                        data_all(bdms_fbc_result.getDtvalues());
//                        calResult.setMaxZs(Collections.max(values));
//                    }
//                    //获取values平均值
//                    Double avg;
//                    if (values != null) {
//                        for (int i = 0; i < values.size(); i++) {
//                            try {
//                                Date date = format.parse(StartTime);
//                                calendar.setTime(date);
//                                calendar.add(Calendar.HOUR, +i);
//                                dataList.add(new Data(format.format(calendar.getTime()), values.get(i)));
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    }
//                    dataList.sort(Comparator.comparing(Data::getTM));
//                    //站码  分组
//                    String datacode = bdms_st_sensor_bs.stream().filter(BDMS_ST_SENSOR_B -> BDMS_ST_SENSOR_B.getStcd().equals(stcd)).findAny().orElse(null).getDatacode();
//                    List<ST_TIDE_R> st_tide_rs = st_tide_rList.stream().filter(ST_TIDE_R -> ST_TIDE_R.getStcd().equals(datacode) && ST_TIDE_R.getMin().equals(min)).collect(Collectors.toList());
//                    List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFs = bdmsStAstrotdFList.stream().filter(BDMS_ST_ASTROTD_F -> BDMS_ST_ASTROTD_F.getStcd().equals(stcd)).collect(Collectors.toList());
//                    for (BDMS_ST_ASTROTD_F bdmsStAstrotdF : bdmsStAstrotdFs) {
//                        FtdzTime = bdmsStAstrotdF.getYmdh();
//                        for (Data data : dataList) {
//                            DataTime = data.getTM();
//                            if (bdmsStAstrotdF.getFtdz() != null) {
//                                //设置高低潮
//                                if (bdmsStAstrotdF.getHltdmk() != null && bdmsStAstrotdF.getHltdmk() > 0) {
//                                    //
//                                    PointResult pointHLResult = new PointResult();
//                                    pointHLResult.setTm(bdmsStAstrotdF.getYmdh());
//                                    //System.out.println(pointHLResult.getTm()+"hlp");
//                                    pointHLResult.setTwc(bdmsStAstrotdF.getFtdz());
//                                    pointHLResults.add(pointHLResult);
//                                } else {
//                                    //设置天文潮预报对象
//                                    PointResult pointResult = new PointResult();
//                                    Data twcData  = new Data();
//                                    Data tdzData  = new Data();
//                                    pointResult.setTm(bdmsStAstrotdF.getYmdh());
//                                    pointResult.setTwc(bdmsStAstrotdF.getFtdz());
//                                    twcData.setTM(bdmsStAstrotdF.getYmdh());
//                                    twcData.setValue(Double.valueOf(String.format("%.4f",bdmsStAstrotdF.getFtdz())));
//                                    String TM = FtdzTime;
//                                    if (st_tide_rs.size() > 0) {
//                                        ST_TIDE_R st_tide_r = st_tide_rs.stream().filter(ST_TIDE_R -> ST_TIDE_R.getTm().substring(0,19).equals(TM.substring(0, 19))).findAny().orElse(null);
//                                        //通过时间获取数据
//                                        if (st_tide_r != null) {
//                                            pointResult.setTdz(st_tide_r.getTdz());
//                                            tdzData.setValue(Double.valueOf(String.format("%.4f",st_tide_r.getTdz())));
//                                            tdzData.setTM(st_tide_r.getTm());
//                                        }
//                                    }
//                                    Data datas = dataList.stream().filter(Data -> Data.getTM().equals(TM)).findAny().orElse(null);
//                                    if (datas != null) {
//                                        Data zsData  = new Data();
//                                        Data ftdzData  = new Data();
//                                        if (datas.getTM().equals(FtdzTime)) {
//                                            pointResult.setTm(datas.getTM());
//                                            // System.out.println(pointResult.getTm()+"p");
//                                            pointResult.setZs(datas.getValue());
//                                            zsData.setTM(datas.getTM());
//                                            zsData.setValue(Double.valueOf(String.format("%.4f",datas.getValue())));
//                                            zsDatas.add(zsData);
//                                            double a = pointResult.getZs();
//                                            double b = bdmsStAstrotdF.getFtdz();
//                                            float a1 = (float) a;
//                                            float b1 = (float) b;
//                                            pointResult.setFtdz(Double.parseDouble(String.format("%.4f", a1 + b1)));
//                                            ftdzData.setValue(Double.parseDouble(String.format("%.4f", a1 + b1)));
//                                            ftdzData.setTM(datas.getTM());
//                                            ftdzDatas.add(ftdzData);
//                                        }
//                                    }
//                                    //特征值集合
//                                    pointResults.add(pointResult);
//                                    twcDatas.add(twcData);
//                                    tdzDatas.add(tdzData);
//                                    break;
//                                }
//                                break;
//                            }
//
//                        }
//                        // break;
//                    }
//                    zschartData.setValueDatas(zsDatas);
//                    twcchartData.setValueDatas(twcDatas);
//                    ftdzchartData.setValueDatas(ftdzDatas);
//                    tdzcartData.setValueDatas(tdzDatas);
//                    chartDatas.add(zschartData);
//                    chartDatas.add(twcchartData);
//                    chartDatas.add(ftdzchartData);
//                    chartDatas.add(tdzcartData);
//                    System.out.println("chartDatas"+chartDatas);
//                    //gouzao    PointHLResults 作业预报开始时间 结束之间 范围的数据  List  gouzao
//                    //判断
//                    try {
//                        calendar.setTime(format.parse(StartTime));
//                        calendar.add(Calendar.HOUR, -1);
//                        Date start = calendar.getTime();
//                        calendar.setTime(format.parse(EndTime));
//                        calendar.add(Calendar.HOUR, -1);
//                        Date end = calendar.getTime();
//                        List<PointResult> pointResults1 = pointResults.stream().filter(
//                                PointResult -> {
//                                    try {
//                                        return format.parse(PointResult.getTm()).after(start)
//                                                && format.parse(PointResult.getTm()).before(end);
//                                    } catch (ParseException e) {
//                                        e.printStackTrace();
//                                    }
//                                    return false;
//                                }).collect(Collectors.toList());
//                        List<PointResult> pointHLResults1 = pointHLResults.stream().filter(
//                                PointResult -> {
//                                    try {
//                                        return start.before(format.parse(PointResult.getTm())) &&
//                                                start.before(format.parse(PointResult.getTm()));
//                                    } catch (ParseException e) {
//                                        e.printStackTrace();
//                                    }
//                                    return false;
//                                }).collect(Collectors.toList());
//                        //   List<PointResult> pointHLResults2 = new ArrayList<>();
//                        for (int i = 0; i < pointHLResults1.size(); i++) {
//                            PointResult pointHLResult = new PointResult();
//                            String pointHLResultsYear = pointHLResults1.get(i).getTm().substring(0, 16);
//                            boolean res = Integer.parseInt(pointHLResultsYear.substring(14, 16)) >= 30;
//                            String time = pointHLResultsYear.substring(0, 13) + ":00:00.0";
//                            Date Time = format.parse(time);
//                            calendar.setTime(Time);
//                            if (res) {
//                                calendar.add(Calendar.HOUR, +1);
//                            }
//                            String day = format.format(calendar.getTime());
//                            //根据日期去获取对应的逐时
//                            PointResult pointResult = pointResults1.stream().filter(PointResult -> PointResult.getTm().equals(day)).findAny().orElse(null);
//                            if (pointResult != null) {
//                                pointHLResult.setTm(pointHLResults1.get(i).getTm());
//                                String tm = pointHLResult.getTm();
//                                pointHLResult.setZs(pointResult.getZs());
//                                pointHLResult.setTwc(pointHLResults1.get(i).getTwc());
//                                pointHLResult.setFtdz(pointHLResult.getZs() + pointHLResult.getTwc());
//                                for (PointResult pointHLs : pointHLResults) {
//                                    if (pointHLs.getTm().equals(tm)) {
//                                        pointHLs.setTm(tm);
//                                        pointHLs.setTwc(pointHLResult.getTwc());
//                                        pointHLs.setZs(pointHLResult.getZs());
//                                        pointHLs.setFtdz(pointHLs.getZs() + pointHLs.getTwc());
//                                    }
//                                }
//                            }
//                        }
////                        calResult.setPointResults(pointResults);
////                        calResult.setPointHLResults(pointHLResults);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//
//                    List<PointResult> pointResultsTwc = pointResults.stream().filter(PointResult -> PointResult.getTwc() != null).collect(Collectors.toList());
//                    PointResult poTwc = pointResultsTwc.stream().max(Comparator.comparing(PointResult::getTwc)).orElse(null);
//                    if (poTwc != null) {
//                        calResult.setMaxTwcTm(poTwc.getTm());
//                        calResult.setMaxTwc(poTwc.getTwc());
//                    }
//                    List<PointResult> pointResultsZs = pointResults.stream().filter(PointResult -> PointResult.getZs() != null).collect(Collectors.toList());
//                    PointResult poZs = pointResultsZs.stream().max(Comparator.comparing(PointResult::getZs)).orElse(null);
//                    if (poZs != null) {
//                        calResult.setMaxZsTm(poZs.getTm());
//                        calResult.setMaxZs(poZs.getZs());
//                    }
//
//                    List<PointResult> pointResultsFtdz =pointResults.stream().filter(PointResult -> PointResult.getFtdz() != null).collect(Collectors.toList());
//                    PointResult poFtzd = pointResultsFtdz.stream().max(Comparator.comparing(PointResult::getFtdz)).orElse(null);
//                    if (poFtzd != null) {
//                        calResult.setMaxFtdzTm(poFtzd.getTm());
//                        calResult.setMaxFtdz(poFtzd.getFtdz());
//                    }
//
//                    calResult.setChartDatas(chartDatas);
//                    calResults.add(calResult);
//                }
//
//            }
//        }
        } else if (DBType == 0 || DBType == null) {
            List<BDMS_FBC_RESULT_P> bdms_fbc_results = bdms_fbc_result_pService.selecTBySchemeId(calSchemeId, stationCodes);
            List<String> stcds = new ArrayList<>();
            for (BDMS_FBC_RESULT_P bdms_fbc_result : bdms_fbc_results) {
                stcds.add(bdms_fbc_result.getPtkey());
            }
            String StartTime = null;
            String EndTime = null;
            //预报增水
            String startTime = null;
            //查询预报增水值
            //获取预报方案  新表
            Integer typhoonId = null;
            String Forecasttime = null;
            List<BDMS_CALCULATESCHEME_M1> bdms_fbc_result_schemes = bdms_calculatescheme_mService.selectShcemeByPidCalID(pid, calSchemeId);
            String param = bdms_fbc_result_schemes.get(0).getParams();
            String[] params = param.split(",");
            typhoonId = Integer.valueOf(params[0]);
            BDMS_FBC_TFINFO_B bdmsFbcTfinfoB = bdms_fbc_tfinfo_bService.queryById(String.valueOf(typhoonId));

            for (BDMS_CALCULATESCHEME_M1 bdms_fbc_result_scheme : bdms_fbc_result_schemes) {
                StartTime = bdms_fbc_result_scheme.getDtmforecast();
//               String param = bdms_fbc_result_scheme.getParams();
//               String[] params =param.split(",");
//                typhoonId = Integer.valueOf(params[0]);
                Forecasttime = bdms_fbc_result_scheme.getDtmforecast();
                try {
                    calendar.setTime(format.parse(StartTime));
                    calendar.add(Calendar.DATE, -backDays);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                startTime = format.format(calendar.getTime());
                EndTime = bdms_fbc_result_scheme.getDtmend();

            }

            //获取到站码集合后，去调用获取实测和天文潮数据
            //获取实测
            List<ST_TIDE_R> st_tide_rList = st_tide_rService.selectByStcd(Stcds, startTime, EndTime);
            String min = "00";
            //两个条件
            //获取天文超数据
            List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFList = bdms_st_astrotd_fService.selectFTDZ(stationCodes, startTime, EndTime, TwcDept);
            //获取高低潮
            //构造比较日期
            String TdzTime;
            String FtdzTime;
            String DataTime;
            //获取到实测和天文潮后构造 PointResult
            //Listdata
            List<Data> dataList = new ArrayList<>();

            if (bdmsStAstrotdFList.size() > 0) {
                for (String stcd : stationCodes) {
                    List<PointResult> pointResults = new ArrayList<>();
                    List<AccuracyEvaluation> accuracyEvaluations = new ArrayList<>();
                    List<PointResult> pointHLResults = new ArrayList<>();

                    //构造返回对象
                    CalResult calResult = new CalResult();
                    //设置站码
                    calResult.setStationCode(stcd);
                    calResult.setTyphoonId(typhoonId);
                    calResult.setForecastTime(Forecasttime);
                    calResult.setTyphoonName(bdmsFbcTfinfoB.getTfnameC());
                    List<BDMS_FBC_RESULT_P> bdms_fbc_resultsList = bdms_fbc_results.stream().filter(BDMS_FBC_RESULT -> BDMS_FBC_RESULT.getPtkey().equals(stcd)).collect(Collectors.toList());
                    //获取值
                    for (BDMS_FBC_RESULT_P bdms_fbc_result : bdms_fbc_resultsList) {
                        data_all(bdms_fbc_result.getDtvalues());
                        calResult.setMaxZs(Collections.max(values));
                    }
                    //获取values平均值
                    Double avg;
                    if (values != null) {
                        for (int i = 0; i < values.size(); i++) {
                            try {
                                Date date = format.parse(StartTime);
                                calendar.setTime(date);
                                calendar.add(Calendar.HOUR, +i);
                                dataList.add(new Data(format.format(calendar.getTime()), values.get(i)));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    dataList.sort(Comparator.comparing(Data::getTM));
                    //站码  分组
                    String datacode = bdms_st_sensor_bs.stream().filter(BDMS_ST_SENSOR_B -> BDMS_ST_SENSOR_B.getStcd().equals(stcd)).findAny().orElse(null).getDatacode();
                    List<ST_TIDE_R> st_tide_rs = st_tide_rList.stream().filter(ST_TIDE_R -> ST_TIDE_R.getStcd().equals(datacode) && ST_TIDE_R.getMin().equals(min)).collect(Collectors.toList());
                    List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFs = bdmsStAstrotdFList.stream().filter(BDMS_ST_ASTROTD_F -> BDMS_ST_ASTROTD_F.getStcd().equals(stcd)).collect(Collectors.toList());
                    for (BDMS_ST_ASTROTD_F bdmsStAstrotdF : bdmsStAstrotdFs) {
                        FtdzTime = bdmsStAstrotdF.getYmdh();
                        for (Data data : dataList) {
                            DataTime = data.getTM();
                            if (bdmsStAstrotdF.getFtdz() != null) {
                                //设置高低潮
                                if (bdmsStAstrotdF.getHltdmk() != null && bdmsStAstrotdF.getHltdmk() > 0) {
                                    //
                                    PointResult pointHLResult = new PointResult();
                                    pointHLResult.setTm(bdmsStAstrotdF.getYmdh());
                                    //System.out.println(pointHLResult.getTm()+"hlp");
                                    pointHLResult.setTwc(bdmsStAstrotdF.getFtdz());
                                    pointHLResults.add(pointHLResult);
                                } else {
                                    //设置天文潮预报对象
                                    PointResult pointResult = new PointResult();
                                    pointResult.setTm(bdmsStAstrotdF.getYmdh());
                                    pointResult.setTwc(bdmsStAstrotdF.getFtdz());
                                    String TM = FtdzTime;
                                    if (st_tide_rs.size() > 0) {
                                        ST_TIDE_R st_tide_r = st_tide_rs.stream().filter(ST_TIDE_R -> ST_TIDE_R.getTm().substring(0, 19).equals(TM.substring(0, 19))).findAny().orElse(null);
                                        //通过时间获取数据
                                        if (st_tide_r != null) {
                                            pointResult.setTdz(st_tide_r.getTdz());
                                        }
                                    }

                                    Data datas = dataList.stream().filter(Data -> Data.getTM().substring(0, 19).equals(TM.substring(0, 19))).findAny().orElse(null);
                                    if (datas != null) {
                                        if (datas.getTM().equals(FtdzTime)) {
                                            pointResult.setTm(datas.getTM());
                                            // System.out.println(pointResult.getTm()+"p");
                                            pointResult.setZs(datas.getValue());
                                            double a = pointResult.getZs();
                                            double b = bdmsStAstrotdF.getFtdz();
                                            float a1 = (float) a;
                                            float b1 = (float) b;
                                            pointResult.setFtdz(Double.parseDouble(String.format("%.2f", a1 + b1)));
                                        }
                                    }
                                    //特征值集合
                                    pointResults.add(pointResult);
                                    break;
                                }
                                break;
                            }
                        }
                        // break;
                    }
                    //gouzao    PointHLResults 作业预报开始时间 结束之间 范围的数据  List  gouzao
                    //判断
                    try {
                        calendar.setTime(format.parse(StartTime));
                        calendar.add(Calendar.HOUR, -1);
                        Date start = calendar.getTime();
                        calendar.setTime(format.parse(EndTime));
                        calendar.add(Calendar.HOUR, -1);
                        Date end = calendar.getTime();
                        List<PointResult> pointResults1 = pointResults.stream().filter(
                                PointResult -> {
                                    try {
                                        return format.parse(PointResult.getTm()).after(start)
                                                && format.parse(PointResult.getTm()).before(end);
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }
                                    return false;
                                }).collect(Collectors.toList());
                        List<PointResult> pointHLResults1 = pointHLResults.stream().filter(
                                PointResult -> {
                                    try {
                                        return start.before(format.parse(PointResult.getTm())) &&
                                                start.before(format.parse(PointResult.getTm()));
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }
                                    return false;
                                }).collect(Collectors.toList());
                        //   List<PointResult> pointHLResults2 = new ArrayList<>();
                        for (PointResult result : pointHLResults1) {
                            PointResult pointHLResult = new PointResult();
                            String pointHLResultsYear = result.getTm().substring(0, 16);
                            boolean res = Integer.parseInt(pointHLResultsYear.substring(14, 16)) >= 30;
                            String time = pointHLResultsYear.substring(0, 13) + ":00:00.0";
                            Date Time = format.parse(time);
                            calendar.setTime(Time);
                            if (res) {
                                calendar.add(Calendar.HOUR, +1);
                            }
                            String day = format.format(calendar.getTime());
                            //根据日期去获取对应的逐时
                            PointResult pointResult = pointResults1.stream().filter(PointResult -> PointResult.getTm().equals(day)).findAny().orElse(null);
                            if (pointResult != null) {
                                pointHLResult.setTm(result.getTm());
                                String tm = pointHLResult.getTm();
                                pointHLResult.setZs(pointResult.getZs());
                                pointHLResult.setTwc(result.getTwc());
                                pointHLResult.setFtdz(pointHLResult.getZs() + pointHLResult.getTwc());
                                for (PointResult pointHLs : pointHLResults) {
                                    if (pointHLs.getTm().equals(tm)) {
                                        pointHLs.setTm(tm);
                                        pointHLs.setTwc(pointHLResult.getTwc());
                                        pointHLs.setZs(pointHLResult.getZs());
                                        pointHLs.setFtdz(pointHLs.getZs() + pointHLs.getTwc());
                                    }
                                }
                            }
                        }
                        calResult.setPointResults(pointResults);
                        calResult.setPointHLResults(pointHLResults);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    List<PointResult> pointResultsTwc = calResult.getPointResults().stream().filter(PointResult -> PointResult.getTwc() != null).collect(Collectors.toList());
                    PointResult poTwc = pointResultsTwc.stream().max(Comparator.comparing(PointResult::getTwc)).orElse(null);
                    if (poTwc != null) {
                        calResult.setMaxTwcTm(poTwc.getTm());
                        calResult.setMaxTwc(poTwc.getTwc());
                    }
                    List<PointResult> pointResultsZs = calResult.getPointResults().stream().filter(PointResult -> PointResult.getZs() != null).collect(Collectors.toList());
                    PointResult poZs = pointResultsZs.stream().max(Comparator.comparing(PointResult::getZs)).orElse(null);
                    if (poZs != null) {
                        calResult.setMaxZsTm(poZs.getTm());
                        calResult.setMaxZs(poZs.getZs());
                    }
                    List<PointResult> pointResultsFtdz = calResult.getPointResults().stream().filter(PointResult -> PointResult.getFtdz() != null).collect(Collectors.toList());
                    PointResult poFtzd = pointResultsFtdz.stream().max(Comparator.comparing(PointResult::getFtdz)).orElse(null);
                    if (poFtzd != null) {
                        calResult.setMaxFtdzTm(poFtzd.getTm());
                        calResult.setMaxFtdz(poFtzd.getFtdz());
                    }

                    calResults.add(calResult);
                }

            }

        }
        return calResults;
    }

    //获取多个预报方案·结果
    public List<CalResults> getBdms_fbc_result2(int pid, List<String> calSchemeIds, List<String> stationCodes, int TwcDept, int backDays, Integer DBType, Integer stepLength) {
        List<CalResults> calResultsList = new ArrayList<>();
        //构造日期函数
        // 日期格式转换
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = new GregorianCalendar();

        //查询结果
        //增水数据
        //获取取数码
        List<String> Stcds = new ArrayList<>();
        List<BDMS_ST_SENSOR_B> bdms_st_sensor_bs = bdms_st_sensor_bService.selectByStcds(stationCodes);
        for (BDMS_ST_SENSOR_B bdms_st_sensor_b : bdms_st_sensor_bs) {
            Stcds.add(bdms_st_sensor_b.getDatacode());
        }
        if (DBType == 0) {
            for (String calSchemeId : calSchemeIds) {
                CalResults cal = new CalResults();
                cal.setCalSchemeId(calSchemeId);
                //构造返回对象
                List<CalResult> calResults = new ArrayList<>();
                List<BDMS_FBC_RESULT_P> bdms_fbc_results = bdms_fbc_result_pService.selecTBySchemeId(calSchemeId, stationCodes);
                List<String> stcds = new ArrayList<>();
                for (BDMS_FBC_RESULT_P bdms_fbc_result : bdms_fbc_results) {
                    stcds.add(bdms_fbc_result.getPtkey());
                }
                String StartTime = null;
                String EndTime = null;
                //预报增水
                String startTime = null;
                //查询预报增水值
                //获取预报方案  新表
                Integer typhoonId = null;
                String Forecasttime = null;
                List<BDMS_CALCULATESCHEME_M1> bdms_fbc_result_schemes = bdms_calculatescheme_mService.selectShcemeByPidCalID(pid, calSchemeId);
                String param = bdms_fbc_result_schemes.get(0).getParams();
                String[] params = param.split(",");
                typhoonId = Integer.valueOf(params[0]);
                cal.setForecastDepartment(params[1]);
                cal.setCalSchemeName(bdms_fbc_result_schemes.get(0).getCschemenm());
                cal.setForecastTime(bdms_fbc_result_schemes.get(0).getDtmforecast());
                cal.setTyphoonId(String.valueOf(typhoonId));
                cal.setModelPar(df.format(Double.valueOf(params[2])));
                BDMS_FBC_TFINFO_B bdmsFbcTfinfoB = bdms_fbc_tfinfo_bService.queryById(String.valueOf(typhoonId));
                cal.setTyphoonName(bdmsFbcTfinfoB.getTfnameC());
                BDMS_FBC_OCEANMODEL_B bdmsFbcOceanmodelB = bdms_fbc_oceanmodel_bService.getModelInfoByModelId(pid,bdms_fbc_result_schemes.get(0).getMdid());
                cal.setModelAbb(bdmsFbcOceanmodelB.getModelabb());
                for (BDMS_CALCULATESCHEME_M1 bdms_fbc_result_scheme : bdms_fbc_result_schemes) {
                    StartTime = bdms_fbc_result_scheme.getDtmforecast();
                    Forecasttime = bdms_fbc_result_scheme.getDtmforecast();
                    try {
                        calendar.setTime(format.parse(StartTime));
                        calendar.add(Calendar.DATE, -backDays);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    startTime = format.format(calendar.getTime());
                    EndTime = bdms_fbc_result_scheme.getDtmend();

                }
                //获取到站码集合后，去调用获取实测和天文潮数据
                //获取实测
                List<ST_TIDE_R> st_tide_rList = st_tide_rService.selectByStcd(Stcds, startTime, EndTime);
                String min = "00";
                //两个条件
                //获取天文超数据
                List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFList = bdms_st_astrotd_fService.selectFTDZ(stationCodes, startTime, EndTime, TwcDept);
                //获取高低潮
                //构造比较日期
                String TdzTime;
                String FtdzTime;
                String DataTime;
                //获取到实测和天文潮后构造 PointResult
                //Listdata
                List<Data> dataList = new ArrayList<>();

                if (bdmsStAstrotdFList.size() > 0) {
                    for (String stcd : stationCodes) {
                        List<PointResult> pointResults = new ArrayList<>();
                        List<AccuracyEvaluation> accuracyEvaluations = new ArrayList<>();
                        List<PointResult> pointHLResults = new ArrayList<>();
                        //构造返回对象
                        CalResult calResult = new CalResult();
                        //设置站码
                        calResult.setStationCode(stcd);
                        calResult.setTyphoonId(typhoonId);
                        calResult.setForecastTime(Forecasttime);
                        calResult.setTyphoonName(bdmsFbcTfinfoB.getTfnameC());

                        List<BDMS_FBC_RESULT_P> bdms_fbc_resultsList = bdms_fbc_results.stream().filter(BDMS_FBC_RESULT -> BDMS_FBC_RESULT.getPtkey().equals(stcd)).collect(Collectors.toList());
                        //获取值
                        for (BDMS_FBC_RESULT_P bdms_fbc_result : bdms_fbc_resultsList) {
                            if (bdms_fbc_result!=null){
                                data_all(bdms_fbc_result.getDtvalues());
                                //获取values平均值
                                Double avg;
                                if (values != null) {
                                    for (int i = 0; i < values.size(); i++) {
                                        try {
                                            Date date = format.parse(StartTime);
                                            calendar.setTime(date);
                                            calendar.add(Calendar.HOUR, +i);
                                            dataList.add(new Data(format.format(calendar.getTime()), values.get(i)));
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                                dataList.sort(Comparator.comparing(Data::getTM));
                                System.out.println("增水数据:"+dataList);
                            }
                        }

                        //站码  分组
                        String datacode = bdms_st_sensor_bs.stream().filter(BDMS_ST_SENSOR_B -> BDMS_ST_SENSOR_B.getStcd().equals(stcd)).findAny().orElse(null).getDatacode();
                        List<ST_TIDE_R> st_tide_rs = st_tide_rList.stream().filter(ST_TIDE_R -> ST_TIDE_R.getStcd().equals(datacode) && ST_TIDE_R.getMin().equals(min)).collect(Collectors.toList());
                        List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFs = bdmsStAstrotdFList.stream().filter(BDMS_ST_ASTROTD_F -> BDMS_ST_ASTROTD_F.getStcd().equals(stcd)).collect(Collectors.toList());
                        for (BDMS_ST_ASTROTD_F bdmsStAstrotdF : bdmsStAstrotdFs) {
                            FtdzTime = bdmsStAstrotdF.getYmdh();
                            for (Data data : dataList) {
                                DataTime = data.getTM();
                                if (bdmsStAstrotdF.getFtdz() != null) {
                                    //设置高低潮
                                    if (bdmsStAstrotdF.getHltdmk() != null && bdmsStAstrotdF.getHltdmk() > 0) {
                                        //
                                        PointResult pointHLResult = new PointResult();
                                        pointHLResult.setTm(bdmsStAstrotdF.getYmdh());
                                        //System.out.println(pointHLResult.getTm()+"hlp");
                                        pointHLResult.setTwc(bdmsStAstrotdF.getFtdz());
                                        pointHLResults.add(pointHLResult);
                                    } else {
                                        //设置天文潮预报对象
                                        PointResult pointResult = new PointResult();
                                        pointResult.setTm(bdmsStAstrotdF.getYmdh());
                                        pointResult.setTwc(bdmsStAstrotdF.getFtdz());
                                        String TM = FtdzTime;
                                        if (st_tide_rs.size() > 0) {
                                            ST_TIDE_R st_tide_r = st_tide_rs.stream().filter(ST_TIDE_R -> ST_TIDE_R.getTm().substring(0, 19).equals(TM.substring(0, 19))).findAny().orElse(null);
                                            //通过时间获取数据
                                            if (st_tide_r != null) {
                                                pointResult.setTdz(st_tide_r.getTdz());
                                            }
                                        }
                                        Data datas = dataList.stream().filter(Data -> Data.getTM().equals(TM)).findAny().orElse(null);
                                        if (datas != null) {
                                            if (datas.getTM().equals(FtdzTime)) {
                                                pointResult.setTm(datas.getTM());
                                                // System.out.println(pointResult.getTm()+"p");
                                                pointResult.setZs(datas.getValue());
                                                double a = pointResult.getZs();
                                                double b = bdmsStAstrotdF.getFtdz();
                                                float a1 = (float) a;
                                                float b1 = (float) b;
                                                pointResult.setFtdz(Double.parseDouble(String.format("%.2f", a1 + b1)));
                                            }
                                        }
                                        //特征值集合
                                        pointResults.add(pointResult);
                                        break;
                                    }
                                    break;
                                }
                            }
                            // break;
                        }
                        //判断
                        try {
                            calendar.setTime(format.parse(StartTime));
                            calendar.add(Calendar.HOUR, -1);
                            Date start = calendar.getTime();
                            calendar.setTime(format.parse(EndTime));
                            calendar.add(Calendar.HOUR, -1);
                            Date end = calendar.getTime();
                            List<PointResult> pointResults1 = pointResults.stream().filter(
                                    PointResult -> {
                                        try {
                                            return format.parse(PointResult.getTm()).after(start)
                                                    && format.parse(PointResult.getTm()).before(end);
                                        } catch (ParseException e) {
                                            e.printStackTrace();
                                        }
                                        return false;
                                    }).collect(Collectors.toList());
                            List<PointResult> pointHLResults1 = pointHLResults.stream().filter(
                                    PointResult -> {
                                        try {
                                            return start.before(format.parse(PointResult.getTm())) &&
                                                    start.before(format.parse(PointResult.getTm()));
                                        } catch (ParseException e) {
                                            e.printStackTrace();
                                        }
                                        return false;
                                    }).collect(Collectors.toList());

                            for (PointResult result : pointHLResults1) {
                                PointResult pointHLResult = new PointResult();
                                String pointHLResultsYear = result.getTm().substring(0, 16);
                                boolean res = Integer.parseInt(pointHLResultsYear.substring(14, 16)) >= 30;
                                String time = pointHLResultsYear.substring(0, 13) + ":00:00.0";
                                Date Time = format.parse(time);
                                calendar.setTime(Time);
                                if (res) {
                                    calendar.add(Calendar.HOUR, +1);
                                }
                                String day = format.format(calendar.getTime());
                                //根据日期去获取对应的逐时
                                PointResult pointResult = pointResults1.stream().filter(PointResult -> PointResult.getTm().equals(day)).findAny().orElse(null);
                                if (pointResult != null) {
                                    pointHLResult.setTm(result.getTm());
                                    String tm = pointHLResult.getTm();
                                    pointHLResult.setZs(pointResult.getZs());
                                    pointHLResult.setTwc(result.getTwc());
                                    pointHLResult.setFtdz(pointHLResult.getZs() + pointHLResult.getTwc());
                                    for (PointResult pointHLs : pointHLResults) {
                                        if (pointHLs.getTm().equals(tm)) {
                                            pointHLs.setTm(tm);
                                            pointHLs.setTwc(pointHLResult.getTwc());
                                            pointHLs.setZs(pointHLResult.getZs());
                                            pointHLs.setFtdz(pointHLs.getZs() + pointHLs.getTwc());
                                        }
                                    }
                                }
                            }

                            calResult.setPointResults(pointResults);
                            calResult.setPointHLResults(pointHLResults);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        List<PointResult> pointResultsTwc = calResult.getPointResults().stream().filter(PointResult -> PointResult.getTwc() != null).collect(Collectors.toList());
                        PointResult poTwc = pointResultsTwc.stream().max(Comparator.comparing(PointResult::getTwc)).orElse(null);
                        if (poTwc != null) {
                            calResult.setMaxTwcTm(poTwc.getTm());
                            calResult.setMaxTwc(poTwc.getTwc());
                        }
                        List<PointResult> pointResultsZs = calResult.getPointResults().stream().filter(PointResult -> PointResult.getZs() != null).collect(Collectors.toList());
                        PointResult poZs = pointResultsZs.stream().max(Comparator.comparing(PointResult::getZs)).orElse(null);
                        if (poZs != null) {
                            calResult.setMaxZsTm(poZs.getTm());
                            calResult.setMaxZs(poZs.getZs());
                        }
                        List<PointResult> pointResultsFtdz = calResult.getPointResults().stream().filter(PointResult -> PointResult.getFtdz() != null).collect(Collectors.toList());
                        PointResult poFtzd = pointResultsFtdz.stream().max(Comparator.comparing(PointResult::getFtdz)).orElse(null);
                        if (poFtzd != null) {
                            calResult.setMaxFtdzTm(poFtzd.getTm());
                            calResult.setMaxFtdz(poFtzd.getFtdz());
                        }
                        calResults.add(calResult);
                    }
                }
                cal.setCalResults(calResults);
                calResultsList.add(cal);
            }
        }
        return calResultsList;
    }




    public List<Data> addData(List<Double> values, String forecastTime) {
        List<Data> dataList = new ArrayList<>();
        if (values != null) {
            for (int i = 0; i < values.size(); i++) {
                try {
                    Date date = format.parse(forecastTime);
                    calendar.setTime(date);
                    calendar.add(Calendar.HOUR, +i);
                    System.out.println(new Data(format.format(calendar.getTime()), values.get(i)));
                    dataList.add(new Data(format.format(calendar.getTime()), values.get(i)));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            dataList.sort(Comparator.comparing(Data::getTM));
        }
        return dataList;
    }

    //获取最新一条方案
    public CalSchemeInfo getNewestCalSchemeInfo(Integer pid, Integer tfid, String time, String modelId, Integer DBType,String area) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.s");
        Calendar calendar = new GregorianCalendar();
        CalSchemeInfo calSchemeInfo = new CalSchemeInfo();
        if (DBType == 1) {
            BDMS_FBC_RESULT_SCHEME bdms_fbc_result_scheme = null;
            BDMS_FBC_RESULT_SCHEME bdms_fbc_result_schemByPid = bdms_fbc_result_schemeService.selectLatestOneBySchemeId(pid, tfid, time, Integer.parseInt(modelId));
            if (bdms_fbc_result_schemByPid != null) {
                bdms_fbc_result_scheme = bdms_fbc_result_schemByPid;
            } else {
                BDMS_FBC_RESULT_SCHEME bdms_fbc_result_schemByFlag = bdms_fbc_result_schemeService.selectLatestOneByFlag(pid, tfid, time, Integer.parseInt(modelId));
                bdms_fbc_result_scheme = bdms_fbc_result_schemByFlag;
            }
            if (bdms_fbc_result_scheme != null) {
                calSchemeInfo.setCalSchemeId(String.valueOf(bdms_fbc_result_scheme.getSchemeId()));
                calSchemeInfo.setTyphoonId(String.valueOf(bdms_fbc_result_scheme.getTfid()));
                calSchemeInfo.setForecastTime(bdms_fbc_result_scheme.getYmdhm());
                try {
                    Date ForecastEndTM = format.parse(bdms_fbc_result_scheme.getYmdhm());
                    calendar.setTime(ForecastEndTM);
                    calendar.add(Calendar.HOUR, +bdms_fbc_result_scheme.getCalnum());
                    calSchemeInfo.setForecastEndTime(format.format(calendar.getTime()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                calSchemeInfo.setUserId(String.valueOf(bdms_fbc_result_scheme.getUserId()));
                calSchemeInfo.setModelId(String.valueOf(bdms_fbc_result_scheme.getModelId()));
                calSchemeInfo.setModelPar(String.valueOf(bdms_fbc_result_scheme.getExpparam()));
                calSchemeInfo.setTyphoonDepart(bdms_fbc_result_scheme.getReportDept());
                calSchemeInfo.setState(String.valueOf(bdms_fbc_result_scheme.getState()));
                if (bdms_fbc_result_scheme.getFlag()!=null){
                    calSchemeInfo.setHasArea("1");
                    calSchemeInfo.setHasPublish(1);
                }

                calSchemeInfo.setCalSchemeName(bdms_fbc_result_scheme.getYmdhm().substring(5,16)
                        +","+bdms_fbc_result_scheme.getReportDept()+","+calSchemeInfo.getModelPar());
//                calSchemeInfo.setHasArea(b);
                calSchemeInfo.setRemark("state 0 新建方案、1 计算中、2 计算失败、3 计算成功");
                // calSchemeInfo.setRemark(bdms_fbc_result_scheme.getFlag());
            }
        } else if (DBType == 0) {
            //根据模型id获取最新一条


            BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m = bdms_calculatescheme_mService.selectNewOneByPidModel(pid, String.valueOf(tfid),modelId,area);
            if (bdms_calculatescheme_m != null) {
                String[] a = bdms_calculatescheme_m.getParams().split(",");

                calSchemeInfo.setCalSchemeId(bdms_calculatescheme_m.getCschemeid());
                calSchemeInfo.setUserId(bdms_calculatescheme_m.getUserid());
                calSchemeInfo.setCalSchemeName(bdms_calculatescheme_m.getCschemenm());
                calSchemeInfo.setTyphoonId(a[0]);
                calSchemeInfo.setTyphoonDepart(a[1]);
                calSchemeInfo.setModelPar(df.format(Double.valueOf(a[2])));
                calSchemeInfo.setModelId(bdms_calculatescheme_m.getMdid());
                calSchemeInfo.setForecastOperateTime(bdms_calculatescheme_m.getDtmcalculate());
                calSchemeInfo.setForecastEndTime(bdms_calculatescheme_m.getDtmend());
                calSchemeInfo.setUserName("预报员");
                calSchemeInfo.setFlag(bdms_calculatescheme_m.getFlag());
                //根据modelid获取model名称
                BDMS_FBC_OCEANMODEL_B bdms_fbc_oceanmodel_b =bdms_fbc_oceanmodel_bService.selectByModelId(pid,bdms_calculatescheme_m.getMdid());
                if (bdms_fbc_oceanmodel_b!=null){
                    calSchemeInfo.setModelId(bdms_fbc_oceanmodel_b.getModelid());
                    calSchemeInfo.setModelName(bdms_fbc_oceanmodel_b.getModelnm());
                }
                calSchemeInfo.setForecastTime(bdms_calculatescheme_m.getDtmforecast());
                calSchemeInfo.setState(String.valueOf(bdms_calculatescheme_m.getState()));
                calSchemeInfo.setRemark("state 0 新建方案、1 计算中、2 计算失败、3 计算成功");
                calSchemeInfo.setHasArea(bdms_calculatescheme_m.getIsarea());
                calSchemeInfo.setHasGen(bdms_calculatescheme_m.getIsgen());
                calSchemeInfo.setHasPublish(bdms_calculatescheme_m.getPublish());
            }
        }
        return calSchemeInfo;
    }

    //获取网格数据
    public CalResultGrid getCalResultsByGrid(Integer ProjectId, Integer CalSchemeId, String AreaName,
                                             Integer Dttp, List<Integer> GridIds,
                                             Boolean IsTwc) {
        if (IsTwc == null) {
            IsTwc = true;
        }
        //构造日期函数
        CalResultGrid calResultGrid = new CalResultGrid();
        List<CalResultGridData> calResultGridDatas = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.s");
        Calendar calendar = new GregorianCalendar();
        String StartTime = null;
        String EndTime = null;

        BDMS_FBC_RESULT_SCHEME bdms_fbc_result_scheme = bdms_fbc_result_schemeService.selectTimeByCalShemeId(CalSchemeId);
        try {
            StartTime = bdms_fbc_result_scheme.getYmdhm();
            calendar.setTime(format.parse(StartTime));
            int hour = bdms_fbc_result_scheme.getCalnum();
            calendar.add(Calendar.HOUR, +hour);
            EndTime = format.format(calendar.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<BDMS_FBC_RESULT_A> bdms_fbc_result_as = new ArrayList<>();
        List<BDMS_FBC_ASTROTD_A> bdms_fbc_astrotd_as = new ArrayList<>();
        List<Double> doubles = new ArrayList<>();
        for (int GridId : GridIds) {
            CalResultGridData calResultGridData = new CalResultGridData();
            List<PointResult> pointResults = new ArrayList<>();
            calResultGridData.setGrid(String.valueOf(GridId));
            bdms_fbc_astrotd_as = bdms_fbc_astrotd_aService.selectByGrid(ProjectId, StartTime, EndTime, GridId);
            System.out.println("bdms_fbc_astrotd_as"+bdms_fbc_astrotd_as);
            bdms_fbc_result_as = bdms_fbc_result_aService.getCalResultsByGrid(String.valueOf(CalSchemeId), AreaName, StartTime, EndTime, Dttp, GridId);
            System.out.println("bdms_fbc_result_as"+bdms_fbc_result_as);
            //遍历天文潮数据
            for (BDMS_FBC_ASTROTD_A bdms_fbc_astrotd_a : bdms_fbc_astrotd_as) {
                PointResult pointResult = new PointResult();
                pointResult.setTm(bdms_fbc_astrotd_a.getTm());
                //获取增水
                BDMS_FBC_RESULT_A ba=  bdms_fbc_result_as.stream().filter(bdms_fbc_result_a -> bdms_fbc_result_a.getDttm().equals(bdms_fbc_astrotd_a.getTm())).findAny().orElse(null);
                if (ba!=null){
                    pointResult.setZs(Double.valueOf(String.format("%.4f",Double.parseDouble(ba.getDtvalues())/100)));
                }
                if (IsTwc) {
                    Double twc;
                    //System.out.println("1"+"".equals(bdms_fbc_astrotd_as.get(i).getDtvalues()));
                    if (!"".equals(bdms_fbc_astrotd_a.getDtvalues())) {
                        twc = Double.valueOf(bdms_fbc_astrotd_a.getDtvalues());
                        pointResult.setTwc(Double.valueOf(String.format("%.4f", twc)));
                        Double ftdz =null;
                        if (pointResult.getZs()!=null){
                            ftdz= pointResult.getZs() + pointResult.getTwc();
                        }else {
                            ftdz =pointResult.getTwc();
                        }
                        pointResult.setFtdz(Double.valueOf(String.format("%.4f", ftdz)));
                    }
                }
                pointResults.add(pointResult);
            }

            if (IsTwc){
                double sum = 0.0;
                for (PointResult result : pointResults) {
                    if (result.getTwc() != null) {
                        sum += result.getTwc();
                    }
                }
                doubles.add(Double.valueOf(String.format("%.4f", sum)));
            }



            calResultGridData.setPointResults(pointResults);
            boolean t= pointResults.stream()
                    .map(PointResult::getTdz).allMatch(Objects::nonNull);

            boolean z= pointResults.stream()
                    .map(PointResult::getZs)
                    .allMatch(Objects::nonNull);
            if (t&&z){
                calResultGrid.setRemark("天文潮数据及预报增水数据为空");
            }else if (t){
                    calResultGrid.setRemark("天文潮数据空");
                }else if (!z){
                calResultGrid.setRemark("增水数据空");
            }
            else {
                calResultGrid.setRemark("天文潮数据及预报增水数据正常");
            }


            calResultGridDatas.add(calResultGridData);
        }
        if (doubles.size() > 0) {
            double sum = doubles.stream().mapToDouble(Double::doubleValue).sum();
            double ave = sum / GridIds.size();
            calResultGrid.setAveFtdz(Double.valueOf(String.format("%.4f", ave)));
        }

        calResultGrid.setCalResultGridDatas(calResultGridDatas);
        return calResultGrid;
    }

    public CalResultGrid getCalResultsByGrid2(GridParam gridParam) {

        String calSchemeId = gridParam.getCalSchemeId();
        Integer projectId = gridParam.getProjectId();
        //构造日期函数
        CalResultGrid calResultGrid = new CalResultGrid();
        List<CalResultGridData> calResultGridDatas = new ArrayList<>();


        BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m1 =bdms_calculatescheme_mService.selectShcemeByCalID(calSchemeId);

        if (bdms_calculatescheme_m1!=null) {

            String areaName = gridParam.getAreaName();
            Integer dttp = gridParam.getDttp();


            String startTime = bdms_calculatescheme_m1.getDtmcalculate();
            String endTime = bdms_calculatescheme_m1.getDtmend();

            List<Integer> grids = gridParam.getGridIds();


            List<BDMS_FBC_RESULT_A> bdms_fbc_result_as = new ArrayList<>();
            List<BDMS_FBC_ASTROTD_A> bdms_fbc_astrotd_as = new ArrayList<>();
            List<Double> doubles = new ArrayList<>();
            for (int grid : grids) {
                CalResultGridData calResultGridData = new CalResultGridData();
                List<PointResult> pointResults = new ArrayList<>();
                calResultGridData.setGrid(String.valueOf(grid));
                bdms_fbc_astrotd_as = bdms_fbc_astrotd_aService.selectByGrid(projectId, startTime, endTime, grid);

                bdms_fbc_result_as = bdms_fbc_result_aService.getCalResultsByGrid(calSchemeId, areaName, startTime, endTime, dttp, grid);

                //判断天文潮是否存在数据
                if (bdms_fbc_astrotd_as!=null && bdms_fbc_astrotd_as.size()>0){
                    //遍历天文潮数据
                    for (BDMS_FBC_ASTROTD_A bdms_fbc_astrotd_a : bdms_fbc_astrotd_as) {
                        PointResult pointResult = new PointResult();
                        pointResult.setTm(bdms_fbc_astrotd_a.getTm());
                        //获取增水
                        BDMS_FBC_RESULT_A ba = bdms_fbc_result_as.stream().filter(bdms_fbc_result_a -> bdms_fbc_result_a.getDttm().equals(bdms_fbc_astrotd_a.getTm())).findAny().orElse(null);
                        if (ba != null) {
                            pointResult.setZs(Double.valueOf(String.format("%.4f", Double.parseDouble(ba.getDtvalues()) / 100)));
                        }

                        //System.out.println("1"+"".equals(bdms_fbc_astrotd_as.get(i).getDtvalues()));
                        Double twc;
                        //System.out.println("1"+"".equals(bdms_fbc_astrotd_as.get(i).getDtvalues()));
                        if (!"".equals(bdms_fbc_astrotd_a.getDtvalues())) {
                            twc = Double.valueOf(bdms_fbc_astrotd_a.getDtvalues());
                            pointResult.setTwc(Double.valueOf(String.format("%.4f", twc)));
                            Double ftdz =null;
                            if (pointResult.getZs()!=null){
                                ftdz= pointResult.getZs() + pointResult.getTwc();
                            }else {
                                ftdz =pointResult.getTwc();
                            }
                            pointResult.setFtdz(Double.valueOf(String.format("%.4f", ftdz)));
                        }
                        pointResults.add(pointResult);
                    }
                }
                calResultGridData.setPointResults(pointResults);
                boolean t= pointResults.stream()
                        .map(PointResult::getTdz).allMatch(Objects::nonNull);

                boolean z= pointResults.stream()
                        .map(PointResult::getZs)
                        .allMatch(Objects::nonNull);
                if (t&&z){
                    calResultGrid.setRemark("天文潮数据及预报增水数据为空");
                }else if (t){
                    calResultGrid.setRemark("天文潮数据空");
                }else if (!z){
                    calResultGrid.setRemark("增水数据空");
                }
                else {
                    calResultGrid.setRemark("天文潮数据及预报增水数据正常");
                }


                calResultGridDatas.add(calResultGridData);


            }
            if (doubles.size() > 0) {
                double sum = doubles.stream().mapToDouble(Double::doubleValue).sum();
                double ave = sum / grids.size();
                calResultGrid.setAveFtdz(Double.valueOf(String.format("%.4f", ave)));
            }

            calResultGrid.setCalResultGridDatas(calResultGridDatas);
        }

        return calResultGrid;

    }
    //获取站点潮位
    //站点潮位数据
    public List<StationTideData> getStationTideData(int projectId, List<String> stationCodes, String starTime, String endTime, Integer stepLength) {
        //返回对象
        List<StationTideData> stationTideDatas = new ArrayList<>();
        // 日期格式转换
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = new GregorianCalendar();
        List<PointResult> pointResultsList1 = new ArrayList<>();
        //创建取数码集合
        List<String> datacCodes = new ArrayList<>();
        if (projectId == 1) {
            datacCodes.addAll(stationCodes);
        } else {
            List<BDMS_ST_SENSOR_B> bdms_st_sensor_bs = bdms_st_sensor_bService.selectRealTimeHydrologic29(projectId, stationCodes);
            for (BDMS_ST_SENSOR_B bdms_st_sensor_b : bdms_st_sensor_bs) {
                datacCodes.add(bdms_st_sensor_b.getDatacode());
            }
        }
        //获取预报方案
        BDMS_FBC_RESULT_SCHEME bdms_fbc_result_scheme1 = bdms_fbc_result_schemeService.selectSchemeByTime(projectId, starTime, endTime);
        List<BDMS_FBC_RESULT> bdms_fbc_results = null;
        String ForecasStartTime = null;
        String ForecasEndTime = null;
        if (bdms_fbc_result_scheme1 != null) {
            //获取最新一条方然后去卡时间范围
            try {
                Date s = format.parse(bdms_fbc_result_scheme1.getYmdhm());
                ForecasStartTime = format.format(s);
                calendar.setTime(format.parse(ForecasStartTime));
                calendar.add(Calendar.HOUR, +bdms_fbc_result_scheme1.getCalnum());
                ForecasEndTime = format.format(calendar.getTime());
                //输入的开始结束时间
            } catch (Exception e) {
                e.printStackTrace();
            }
            //获取到计算方案之后去获取增水值
            //计算结果获取增水
            bdms_fbc_results = bdms_fbc_resultService.selecTBySchemeId(bdms_fbc_result_scheme1.getSchemeId(), stationCodes);
            List<String> stcds = new ArrayList<>();
            for (BDMS_FBC_RESULT bdms_fbc_result : bdms_fbc_results) {
                stcds.add(bdms_fbc_result.getStcd());
            }
        }
        //获取天文潮数据
        int TwcDept = 0;
        System.out.println(datacCodes);
        List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFList = bdms_st_astrotd_fService.selectFTDZ(datacCodes, starTime, endTime, TwcDept);
        //站码循环分组
        for (String stcd : datacCodes) {
            List<Data> dataList = new ArrayList<>();
            if (bdms_fbc_results != null) {
                List<BDMS_FBC_RESULT> bdms_fbc_resultsList = bdms_fbc_results.stream().filter(BDMS_FBC_RESULT -> BDMS_FBC_RESULT.getStcd().equals(stcd)).collect(Collectors.toList());
                //获取值
                for (BDMS_FBC_RESULT bdms_fbc_result : bdms_fbc_resultsList) {
                    DATA_All(bdms_fbc_result.getDataAll());
                }
                if (values != null) {
                    for (int i = 0; i < values.size(); i++) {
                        try {
                            Date date = format.parse(ForecasStartTime);
                            //预报时间小于before结束时间  预报结束时间大于 after开始时间
                            if (date.before(format.parse(endTime)) && format.parse(ForecasEndTime).after(format.parse(starTime))) {
                                calendar.setTime(date);
                                calendar.add(Calendar.HOUR, +i);
                                dataList.add(new Data(format.format(calendar.getTime()), values.get(i)));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                dataList.sort(Comparator.comparing(Data::getTM));
            }
            //根据时间来绑定数据
            StationTideData stationTideData = new StationTideData();
            stationTideData.setStationCode(stcd);
            List<PointResult> pointResults = new ArrayList<>();
            List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFs = bdmsStAstrotdFList.stream().filter(BDMS_ST_ASTROTD_F -> BDMS_ST_ASTROTD_F.getStcd().equals(stcd)).collect(Collectors.toList());
            for (int i = 0; i < bdmsStAstrotdFs.size(); i++) {
                String FtdzTime = bdmsStAstrotdFs.get(i).getYmdh();
                if (bdmsStAstrotdFs.get(i).getFtdz() != null) {
                    //获取天文潮
                    if (bdmsStAstrotdFs.get(i).getHltdmk() == 0) {
                        PointResult pointResult = new PointResult();
                        if (stepLength != null) {

                            if (i + 1 < bdmsStAstrotdFs.size()) {
                                String startTM = bdmsStAstrotdFs.get(i).getYmdh();
                                String endTM = null;
                                System.out.println(bdmsStAstrotdFs.get(i + 1).getYmdh().substring(14, 16));
                                if (bdmsStAstrotdFs.get(i + 1).getYmdh().substring(14, 16).equals("00")) {
                                    endTM = bdmsStAstrotdFs.get(i + 1).getYmdh();
                                } else {
                                    try {
                                        Date end = format.parse(bdmsStAstrotdFs.get(i + 1).getYmdh());
                                        end.setMinutes(0);
                                        calendar.setTime(end);
                                        calendar.add(Calendar.HOUR, +1);
                                        endTM = format.format(calendar.getTime()) + ".0";
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }

                                }

                                Double a = bdmsStAstrotdFs.get(i).getFtdz();
                                bdmsStAstrotdFs.stream().filter(BDMS_ST_ASTROTD_F -> BDMS_ST_ASTROTD_F.getYmdh().equals(startTM)).findAny().orElse(null).getFtdz();
                                Double c = bdmsStAstrotdFs.get(i + 1).getFtdz();
                                bdmsStAstrotdFs.stream().filter(BDMS_ST_ASTROTD_F -> BDMS_ST_ASTROTD_F.getYmdh().equals(startTM)).findAny().orElse(null).getFtdz();
                                List<PointResult> pointResultsList = arithmeticUtil.getInterpolation(startTM, endTM, a, c, stepLength, "twc");
                                pointResults.addAll(pointResultsList);
                            }
                        }
                        pointResult.setTm(bdmsStAstrotdFs.get(i).getYmdh());
                        pointResult.setTwc(bdmsStAstrotdFs.get(i).getFtdz());
                        for (int k = 0; k < dataList.size(); k++) {
                            String DataTime = dataList.get(k).getTM();
                            //设置天文潮预报对象
                            String TM = null;
                            try {
                                TM = format.format(format.parse(FtdzTime));
                                ;
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            String time = TM;
                            Data datas = dataList.stream().filter(Data -> Data.getTM().equals(time)).findAny().orElse(null);
                            if (datas != null) {
                                if (datas.getTM().equals(TM)) {
                                    if (datas.getValue() != null) {
                                        pointResult.setZs(datas.getValue());

                                    }
                                    double a = pointResult.getZs();
                                    double b = bdmsStAstrotdFs.get(i).getFtdz();
                                    float a1 = (float) a;
                                    float b1 = (float) b;
                                    pointResult.setFtdz(Double.parseDouble(String.format("%.2f", a1 + b1)));
                                    if (stepLength != null) {
                                        if (i + 1 < bdmsStAstrotdFs.size()) {
                                            String startTM = bdmsStAstrotdFs.get(i).getYmdh();
                                            String endTM = bdmsStAstrotdFs.get(i + 1).getYmdh();
                                            Double ta = null;
                                            Double tc = null;
                                            ta = bdmsStAstrotdFs.get(i).getFtdz();
                                            tc = bdmsStAstrotdFs.get(i + 1).getFtdz();
                                            List<PointResult> pointResultsTwcs = arithmeticUtil.getInterpolation(startTM, endTM, ta, tc, stepLength, "twc");
                                            Double za = null;
                                            Double zc = null;
                                            if (k + 1 < dataList.size()) {
                                                za = dataList.get(k).getValue();
                                                zc = dataList.get(k + 1).getValue();

                                            }
                                            List<PointResult> pointResultsZss = arithmeticUtil.getInterpolation(startTM, endTM, za, zc, stepLength, "zs");
                                            //  pointResults.addAll(pointResultsZs);
                                            //List<PointResult> pointResultsFtzds = arithmeticUtil.getInterpolation(startTM,endTM,fa,fc,stepLength,"ftdz");
                                            for (PointResult pointResultsTwc : pointResultsTwcs) {
                                                for (PointResult pointResultsZs : pointResultsZss) {
                                                    if (pointResultsTwc.getTm().equals(pointResultsZs.getTm())) {
                                                        PointResult newPointResult = new PointResult();
                                                        newPointResult.setTm(pointResultsZs.getTm());
                                                        newPointResult.setZs(pointResultsZs.getZs());
                                                        newPointResult.setTwc(pointResultsTwc.getTwc());
                                                        newPointResult.setFtdz(Double.valueOf(String.format("%.2f", newPointResult.getZs() + newPointResult.getTwc())));
                                                        pointResultsList1.add(newPointResult);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            } else {
                                double b = bdmsStAstrotdFs.get(i).getFtdz();
                                pointResult.setZs(null);
                                pointResult.setFtdz(b);
                            }
                        }
                        pointResults.add(pointResult);
                        pointResults.addAll(pointResultsList1);
                    }
                }
            }
            List<PointResult> maxData = pointResults.stream().filter(PointResult -> PointResult.getFtdz() != null).collect(Collectors.toList());
            PointResult pointResult;
            Data maxData1 = new Data();
            if (maxData.size() > 0) {
                if (maxData.stream().max(Comparator.comparing(PointResult::getFtdz)).orElse(null).getFtdz() != null) {
                    pointResult = pointResults.stream().max(Comparator.comparing(PointResult::getFtdz)).orElse(null);
                    stationTideData.setMaxValueUpper(Double.parseDouble(String.format("%.2f", pointResult.getFtdz() + 0.1)));
                    stationTideData.setMaxVauleLower(Double.parseDouble(String.format("%.2f", pointResult.getFtdz() - 0.1)));
                    maxData1.setTM(pointResult.getTm());
                    maxData1.setValue(pointResult.getFtdz());
                    stationTideData.setMaxTideData(maxData1);
                }
            } else {
                pointResult = pointResults.stream().max(Comparator.comparing(PointResult::getTwc)).orElse(null);
                if (pointResult != null) {
                    stationTideData.setMaxValueUpper(Double.parseDouble(String.format("%.2f", pointResult.getTwc() + 0.1)));
                    stationTideData.setMaxVauleLower(Double.parseDouble(String.format("%.2f", pointResult.getTwc() - 0.1)));
                    if (maxData1.getValue() == null) {
                        maxData1.setTM(pointResult.getTm());
                        maxData1.setValue(pointResult.getTwc());
                        stationTideData.setMaxTideData(maxData1);
                    }
                }
            }
            try {
                pointResult = pointResults.stream().max(Comparator.comparing(PointResult::getZs)).orElse(null);
                if (pointResult != null) {
                    stationTideData.setForecastResults(true);
                }
            } catch (NullPointerException E) {
                stationTideData.setForecastResults(false);
            }
            pointResults.sort(Comparator.comparing(PointResult::getTm));
            stationTideData.setDatas(pointResults);
            stationTideDatas.add(stationTideData);
        }

        return stationTideDatas;
    }

    //获取告警
    public List<Alarm> getNewData(Integer project, List<String> StationCodes, Integer DBType) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = new GregorianCalendar();
        List<Alarm> alarmList = new ArrayList<>();
        List<String> stationCodes = new ArrayList<>();
        List<BDMS_ST_SENSOR_B> bdms_st_sensor_bs = bdms_st_sensor_bService.selectBySTCD29(project, StationCodes);
        for (int i = 0; i < bdms_st_sensor_bs.size(); i++) {
            stationCodes.add(bdms_st_sensor_bs.get(i).getDatacode());
        }
        System.out.println(stationCodes);
        if (DBType==0) {
            List<ST_TIDE_R> st_tide_rs = st_tide_rService.selectNewEstData(StationCodes);
            List<BDMS_ST_SENSORALARM_B> bdms_st_sensoralarm_bs = bdms_st_sensoralarm_bService.selectByStcd(StationCodes, "TDZ", project);
            BDMS_FBC_RESULT_SCHEME bdms_fbc_result_scheme = bdms_fbc_result_schemeService.selectNewOne();
            String startTime = bdms_fbc_result_scheme.getYmdhm();
            try {
                calendar.setTime(format.parse(startTime));
            } catch (Exception e) {
                e.printStackTrace();
            }
            calendar.add(Calendar.HOUR, bdms_fbc_result_scheme.getCalnum());
            String endTime = format.format(calendar.getTime());
            List<BDMS_FBC_RESULT> bdms_fbc_results = bdms_fbc_resultService.selecTBySchemeId(bdms_fbc_result_scheme.getSchemeId(), StationCodes);



            List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFList = bdms_st_astrotd_fService.selectFTDZ(StationCodes, startTime, endTime, 0);
            //查询站名
            List<BDMS_ST_STBPRP_B> bdms_st_stbprp_bs = bdms_st_stbprp_bService.selectStationByProject(project);


            for (String stcd : StationCodes) {
                List<Data> dataList = new ArrayList();
                for (BDMS_FBC_RESULT bdms_fbc_result : bdms_fbc_results) {
                    DATA_All(bdms_fbc_result.getDataAll());
                }
                if (values != null) {
                    for (int i = 0; i < this.values.size(); ++i) {
                        try {
                            Date date = format.parse(bdms_fbc_result_scheme.getYmdhm());
                            calendar.setTime(date);
                            calendar.add(Calendar.HOUR, i);
                            dataList.add(new Data(format.format(calendar.getTime()), values.get(i)));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                dataList.sort(Comparator.comparing(Data::getTM));
                Alarm alarm = new Alarm();
                alarm.setStationCode(stcd);
                //设置站名
                BDMS_ST_STBPRP_B bdms_st_stbprp_b = bdms_st_stbprp_bs.stream().filter(BDMS_ST_STBPRP_B -> BDMS_ST_STBPRP_B.getStcd().equals(stcd)).findAny().orElse(null);
                alarm.setStationName(bdms_st_stbprp_b.getStnm());
                AlarmData alarmData = new AlarmData();
                List<PointResult> pointResults = new ArrayList();
                List<PointResult> pointHLResults = new ArrayList();
                ST_TIDE_R st_tide_r = st_tide_rs.stream().filter(ST_TIDE_R -> ST_TIDE_R.getStcd().equals(stcd)).findAny().orElse(null);
                String ForecastTime = null;
                String ForecastMaxTide = null;
                Date d = null;
                Date fcTime = null;
                Data forecastMaxData = new Data();
                Data data = new Data();
                if (st_tide_r != null) {
                    try {
                        d = format.parse(st_tide_r.getTm());
                        fcTime = format.parse(bdms_fbc_result_scheme.getYmdhm());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    data.setTM(st_tide_r.getTm());
                    data.setValue(st_tide_r.getTdz());
                }
                //设置最新数据
                alarmData.setNewestData(data);
                //获取历史最高潮位
                ST_TIDE_R max = st_tide_rService.selectMAXData(stcd);
                if (max != null) {
                    alarmData.setAllTimeHighTideLevel(String.valueOf(max.getTdz()));
                }
                long c = 3;
                if (d != null) {
                    Long a = d.getTime();
                    Long b = fcTime.getTime();
                    c = (a - b) / 3600000L;
                }
                //设置预报数据
                if (c <= 2) {
                    bdmsStAstrotdFList.stream().filter(BDMS_ST_ASTROTD_F -> BDMS_ST_ASTROTD_F.getStcd().equals(stcd)).collect(Collectors.toList());
                    for (BDMS_ST_ASTROTD_F bdmsStAstrotdF : bdmsStAstrotdFList) {
                        String FtdzTime = bdmsStAstrotdF.getYmdh();
                        for (Data data1 : dataList) {
                            String DataTime = data1.getTM();
                            if (bdmsStAstrotdF.getFtdz() != null) {
                                //设置高低潮
                                if (bdmsStAstrotdF.getHltdmk() != null && bdmsStAstrotdF.getHltdmk() > 0) {
                                    //
                                    PointResult pointHLResult = new PointResult();
                                    pointHLResult.setTm(bdmsStAstrotdF.getYmdh());
                                    //System.out.println(pointHLResult.getTm()+"hlp");
                                    pointHLResult.setTwc(bdmsStAstrotdF.getFtdz());
                                    pointHLResults.add(pointHLResult);
                                } else {
                                    //设置天文潮预报对象
                                    PointResult pointResult = new PointResult();
                                    pointResult.setTm(bdmsStAstrotdF.getYmdh());
                                    pointResult.setTwc(bdmsStAstrotdF.getFtdz());
                                    String TM = FtdzTime;
                                    Data datas = dataList.stream().filter(Data -> Data.getTM().equals(TM)).findAny().orElse(null);
                                    if (datas != null) {
                                        if (datas.getTM().equals(FtdzTime)) {
                                            pointResult.setTm(datas.getTM());
                                            // System.out.println(pointResult.getTm()+"p");
                                            pointResult.setZs(datas.getValue());
                                            double aDouble = pointResult.getZs();
                                            double bDouble = bdmsStAstrotdF.getFtdz();
                                            float a1 = (float) aDouble;
                                            float b1 = (float) bDouble;
                                            pointResult.setFtdz(Double.parseDouble(String.format("%.2f", a1 + b1)));
                                        }
                                    }
                                    //特征值集合
                                    pointResults.add(pointResult);
                                    break;
                                }
                                break;
                            }
                            continue;
                        }
                        // break;
                    }
                    try {
                        calendar.setTime(format.parse(startTime));
                        calendar.add(Calendar.HOUR, -1);
                        Date start = calendar.getTime();
                        calendar.setTime(format.parse(endTime));
                        calendar.add(Calendar.HOUR, -1);
                        Date end = calendar.getTime();
                        List<PointResult> pointResults1 = pointResults.stream().filter((PointResult) -> {
                            try {
                                return format.parse(PointResult.getTm()).after(start) && format.parse(PointResult.getTm()).before(end);
                            } catch (ParseException e) {
                                e.printStackTrace();
                                return false;
                            }
                        }).collect(Collectors.toList());
                        List<PointResult> pointHLResults1 = pointHLResults.stream().filter((PointResult) -> {
                            try {
                                return start.before(format.parse(PointResult.getTm())) && start.before(format.parse(PointResult.getTm()));
                            } catch (ParseException e) {
                                e.printStackTrace();
                                return false;
                            }
                        }).collect(Collectors.toList());

                        for (int i = 0; i < pointHLResults1.size(); ++i) {
                            PointResult pointHLResult = new PointResult();
                            String pointHLResultsYear = (pointHLResults1.get(i)).getTm().substring(0, 16);
                            boolean res = Integer.parseInt(pointHLResultsYear.substring(14, 16)) >= 30;
                            String time = pointHLResultsYear.substring(0, 13) + ":00:00.0";
                            Date Time = format.parse(time);
                            calendar.setTime(Time);
                            if (res) {
                                calendar.add(10, 1);
                            }

                            String day = format.format(calendar.getTime());
                            PointResult pointResult = pointResults1.stream().filter(PointResult -> PointResult.getTm().equals(day)).findAny().orElse(null);
                            if (pointResult != null) {
                                pointHLResult.setTm((pointHLResults1.get(i)).getTm());
                                String tm = pointHLResult.getTm();
                                pointHLResult.setZs(pointResult.getZs());
                                pointHLResult.setTwc((pointHLResults1.get(i)).getTwc());
                                pointHLResult.setFtdz(pointHLResult.getZs() + pointHLResult.getTwc());
                                for (PointResult pointHLs : pointHLResults) {
                                    if (pointHLs.getTm().equals(tm)) {
                                        pointHLs.setTm(tm);
                                        pointHLs.setTwc(pointHLResult.getTwc());
                                        pointHLs.setZs(pointHLResult.getZs());
                                        pointHLs.setFtdz(pointHLs.getZs() + pointHLs.getTwc());
                                    }
                                }

                            }
                        }
                        PointResult pointResult = pointHLResults.stream().max(Comparator.comparing(PointResult::getFtdz)).orElse(null);
                        ForecastTime = pointResult.getTm();
                        ForecastMaxTide = String.valueOf(pointResult.getFtdz());
                        forecastMaxData.setValue(Double.valueOf(ForecastMaxTide));
                        forecastMaxData.setTM(ForecastTime);
                        alarmData.setForecastMaxData(forecastMaxData);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
                System.out.println(forecastMaxData);
                List<BDMS_ST_SENSORALARM_B> bdms_st_sensoralarm_bList = bdms_st_sensoralarm_bs.stream().filter(BDMS_ST_SENSORALARM_Bx ->
                        BDMS_ST_SENSORALARM_Bx.getStcd().equals(stcd)
                ).collect(Collectors.toList());

                for (BDMS_ST_SENSORALARM_B BDMS_ST_SENSORALARM_B : bdms_st_sensoralarm_bList) {
                    if (data.getValue() != null && data.getValue() <= BDMS_ST_SENSORALARM_B.getAlarmvalue()) {
                        alarmData.setAlarmTideData(String.valueOf(BDMS_ST_SENSORALARM_B.getAlarmvalue()));
                        alarmData.setDistanceAlert(String.format("%.2f", Math.abs(data.getValue() - BDMS_ST_SENSORALARM_B.getAlarmvalue())));
                        System.out.println(data.getValue());
                        System.out.println(BDMS_ST_SENSORALARM_B.getAlarmvalue());
                        if (BDMS_ST_SENSORALARM_B.getAlarmlevel().equals("正常")) {
                            alarmData.setAlarmColor("#000000");
                        } else if (BDMS_ST_SENSORALARM_B.getAlarmlevel().equals("黄色预警")) {
                            alarmData.setAlarmColor("#FFBC00");
                        } else if (BDMS_ST_SENSORALARM_B.getAlarmlevel().equals("橙色预警")) {
                            alarmData.setAlarmColor("#FFA500");
                        } else if (BDMS_ST_SENSORALARM_B.getAlarmlevel().equals("红色预警")) {
                            alarmData.setAlarmColor("#FF0000");
                        }
                    }
                    if (forecastMaxData.getValue() != null && forecastMaxData.getValue() >= BDMS_ST_SENSORALARM_B.getAlarmvalue()) {
                        alarmData.setForecastDistanceAlert(String.format("%.2f", Math.abs(data.getValue() - BDMS_ST_SENSORALARM_B.getAlarmvalue())));
                    }
                }
                alarm.setAlarmData(alarmData);
                alarmList.add(alarm);
            }
        } else if (DBType == 1) {

            //获取最新的实测潮位数据
            List<ST_TIDE_R> st_tide_rs = st_tide_rService.selectNewEstData(stationCodes);
            //获取告警状态表
            List<BDMS_ST_SENSORALARM_B> bdms_st_sensoralarm_bs = bdms_st_sensoralarm_bService.selectByStcd(StationCodes, "TDZ", project);
            //获取最新一条计算方案
            BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m1 = bdms_calculatescheme_mService.selectNewOneByPid(project);
            if (bdms_calculatescheme_m1!=null){
                String startTime = bdms_calculatescheme_m1.getDtmforecast();
                String endTime = bdms_calculatescheme_m1.getDtmend();
                //查询增水表
                List<BDMS_FBC_RESULT_P> bdms_fbc_results = bdms_fbc_result_pService.selecTBySchemeId(bdms_calculatescheme_m1.getCschemeid(), StationCodes);

                //获取天文潮数据
                List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFList = bdms_st_astrotd_fService.selectFTDZ(StationCodes, startTime, endTime, 0);
                //查询站名
                List<BDMS_ST_STBPRP_B> bdms_st_stbprp_bs = bdms_st_stbprp_bService.selectStationByProject(project);

                for (String stcd : StationCodes) {
                    List<Data> dataList = new ArrayList<>();
                    for (BDMS_FBC_RESULT_P bdms_fbc_result : bdms_fbc_results) {
                        data_all(bdms_fbc_result.getDtvalues());
                    }
                    if (values != null) {
                        for (int i = 0; i < values.size(); i++) {
                            try {
                                Date date = format.parse(startTime);
                                calendar.setTime(date);
                                calendar.add(Calendar.HOUR, +i);
                                dataList.add(new Data(format.format(calendar.getTime()), values.get(i)));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    dataList.sort(Comparator.comparing(Data::getTM));
                    Alarm alarm = new Alarm();
                    alarm.setStationCode(stcd);
                    //设置站名
                    BDMS_ST_SENSOR_B sensor = bdms_st_sensor_bs.stream().filter(BDMS_ST_SENSOR_B -> BDMS_ST_SENSOR_B.getStcd().equals(stcd)).findAny().orElse(null);
                    String stationcode = sensor.getDatacode();
                    BDMS_ST_STBPRP_B bdms_st_stbprp_b = bdms_st_stbprp_bs.stream().filter(BDMS_ST_STBPRP_B -> BDMS_ST_STBPRP_B.getStcd().equals(stcd)).findAny().orElse(null);
                    alarm.setStationName(bdms_st_stbprp_b.getStnm());
                    AlarmData alarmData = new AlarmData();
                    List<PointResult> pointResults = new ArrayList();
                    List<PointResult> pointHLResults = new ArrayList();
                    ST_TIDE_R st_tide_r = st_tide_rs.stream().filter(ST_TIDE_R -> ST_TIDE_R.getStcd().equals(stationcode)).findAny().orElse(null);
                    String ForecastTime = null;
                    String ForecastMaxTide = null;
                    Date d = null;
                    Date fcTime = null;
                    Data forecastMaxData = new Data();
                    Data data = new Data();
                    if (st_tide_r != null) {
                        try {
                            d = format.parse(st_tide_r.getTm());
                            fcTime = format.parse(startTime);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        data.setTM(st_tide_r.getTm());
                        data.setValue(st_tide_r.getTdz());
                    }
                    //设置最新数据
                    alarmData.setNewestData(data);
                    //获取历史最高潮位
                    ST_TIDE_R max = st_tide_rService.selectMAXData(stationcode);
                    if (max != null) {
                        alarmData.setAllTimeHighTideLevel(String.valueOf(max.getTdz()));
                    }
                    long c = 3;
                    if (d != null) {
                        Long a = d.getTime();
                        Long b = fcTime.getTime();
                        c = (a - b) / 3600000L;
                    }
                    //设置预报数据
                    if (c <= 2) {
                        bdmsStAstrotdFList.stream().filter(BDMS_ST_ASTROTD_F -> BDMS_ST_ASTROTD_F.getStcd().equals(stcd)).collect(Collectors.toList());
                        for (BDMS_ST_ASTROTD_F bdmsStAstrotdF : bdmsStAstrotdFList) {
                            String FtdzTime = bdmsStAstrotdF.getYmdh();
                            for (Data data1 : dataList) {
                                String DataTime = data1.getTM();
                                if (bdmsStAstrotdF.getFtdz() != null) {
                                    //设置高低潮
                                    if (bdmsStAstrotdF.getHltdmk() != null && bdmsStAstrotdF.getHltdmk() > 0) {
                                        //
                                        PointResult pointHLResult = new PointResult();
                                        pointHLResult.setTm(bdmsStAstrotdF.getYmdh());
                                        //System.out.println(pointHLResult.getTm()+"hlp");
                                        pointHLResult.setTwc(bdmsStAstrotdF.getFtdz());
                                        pointHLResults.add(pointHLResult);
                                    } else {
                                        //设置天文潮预报对象
                                        PointResult pointResult = new PointResult();
                                        pointResult.setTm(bdmsStAstrotdF.getYmdh());
                                        pointResult.setTwc(bdmsStAstrotdF.getFtdz());
                                        String TM = FtdzTime;
                                        Data datas = dataList.stream().filter(Data -> Data.getTM().equals(TM)).findAny().orElse(null);
                                        if (datas != null) {
                                            if (datas.getTM().equals(FtdzTime)) {
                                                pointResult.setTm(datas.getTM());
                                                // System.out.println(pointResult.getTm()+"p");
                                                pointResult.setZs(datas.getValue());
                                                double aDouble = pointResult.getZs();
                                                double bDouble = bdmsStAstrotdF.getFtdz();
                                                float a1 = (float) aDouble;
                                                float b1 = (float) bDouble;
                                                pointResult.setFtdz(Double.parseDouble(String.format("%.2f", a1 + b1)));
                                            }
                                        }
                                        //特征值集合
                                        pointResults.add(pointResult);
                                        break;
                                    }
                                    break;
                                }
                                continue;
                            }
                            // break;
                        }
                        try {
                            calendar.setTime(format.parse(startTime));
                            calendar.add(Calendar.HOUR, -1);
                            Date start = calendar.getTime();
                            calendar.setTime(format.parse(endTime));
                            calendar.add(Calendar.HOUR, -1);
                            Date end = calendar.getTime();
                            List<PointResult> pointResults1 = pointResults.stream().filter((PointResult) -> {
                                try {
                                    return format.parse(PointResult.getTm()).after(start) && format.parse(PointResult.getTm()).before(end);
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                    return false;
                                }
                            }).collect(Collectors.toList());
                            List<PointResult> pointHLResults1 = pointHLResults.stream().filter((PointResult) -> {
                                try {
                                    return start.before(format.parse(PointResult.getTm())) && start.before(format.parse(PointResult.getTm()));
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                    return false;
                                }
                            }).collect(Collectors.toList());

                            for (PointResult result : pointHLResults1) {
                                PointResult pointHLResult = new PointResult();
                                String pointHLResultsYear = result.getTm().substring(0, 16);
                                boolean res = Integer.parseInt(pointHLResultsYear.substring(14, 16)) >= 30;
                                String time = pointHLResultsYear.substring(0, 13) + ":00:00.0";
                                Date Time = format.parse(time);
                                calendar.setTime(Time);
                                if (res) {
                                    calendar.add(10, 1);
                                }
                                String day = format.format(calendar.getTime());
                                PointResult pointResult = pointResults1.stream().filter(PointResult -> PointResult.getTm().equals(day)).findAny().orElse(null);
                                if (pointResult != null) {
                                    pointHLResult.setTm(result.getTm());
                                    String tm = pointHLResult.getTm();
                                    pointHLResult.setZs(pointResult.getZs());
                                    pointHLResult.setTwc(result.getTwc());
                                    pointHLResult.setFtdz(pointHLResult.getZs() + pointHLResult.getTwc());
                                    for (PointResult pointHLs : pointHLResults) {
                                        if (pointHLs.getTm().equals(tm)) {
                                            pointHLs.setTm(tm);
                                            pointHLs.setTwc(pointHLResult.getTwc());
                                            pointHLs.setZs(pointHLResult.getZs());
                                            pointHLs.setFtdz(pointHLs.getZs() + pointHLs.getTwc());
                                        }
                                    }
                                }
                            }
                            PointResult pointResult = null;
                            if (!pointHLResults.isEmpty()) {
                                pointResult = pointHLResults.get(0);
                                if (pointResult.getFtdz() == null) {
                                    pointResult = null;
                                } else {
                                    for (int i = 1; i < pointHLResults.size(); i++) {
                                        if (pointHLResults.get(i).getFtdz() != null && pointHLResults.get(i).getFtdz() > pointResult.getFtdz()) {
                                            pointResult = pointHLResults.get(i);
                                        }
                                    }
                                    ForecastTime = pointResult.getTm();
                                    ForecastMaxTide = String.valueOf(pointResult.getFtdz());
                                    forecastMaxData.setValue(Double.valueOf(ForecastMaxTide));
                                    forecastMaxData.setTM(ForecastTime);
                                }
                            }
                            alarmData.setForecastMaxData(forecastMaxData);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        //卡死程序的break
                        //break;
                    }

                    List<BDMS_ST_SENSORALARM_B> bdms_st_sensoralarm_bList = bdms_st_sensoralarm_bs.stream().filter(BDMS_ST_SENSORALARM_Bx ->
                            BDMS_ST_SENSORALARM_Bx.getStcd().equals(stcd)
                    ).collect(Collectors.toList());

                    for (BDMS_ST_SENSORALARM_B BDMS_ST_SENSORALARM_B : bdms_st_sensoralarm_bList) {
                        alarmData.setAlarmTideData(String.valueOf(BDMS_ST_SENSORALARM_B.getAlarmvalue()));
                        if (data.getValue() != null && data.getValue() <= BDMS_ST_SENSORALARM_B.getAlarmvalue()) {
                            alarmData.setDistanceAlert(String.format("%.2f", Math.abs(data.getValue() - BDMS_ST_SENSORALARM_B.getAlarmvalue())));
                            switch (BDMS_ST_SENSORALARM_B.getAlarmlevel()) {
                                case "正常":
                                    alarmData.setAlarmColor("#000000");
                                    break;
                                case "黄色预警":
                                    alarmData.setAlarmColor("#FFBC00");
                                    break;
                                case "橙色预警":
                                    alarmData.setAlarmColor("#FFA500");
                                    break;
                                case "红色预警":
                                    alarmData.setAlarmColor("#FF0000");
                                    break;
                            }
                        }
                        if (forecastMaxData.getValue() != null && forecastMaxData.getValue() >= BDMS_ST_SENSORALARM_B.getAlarmvalue()) {
                            alarmData.setForecastDistanceAlert(String.format("%.2f", Math.abs(data.getValue() - BDMS_ST_SENSORALARM_B.getAlarmvalue())));
                        }
                    }
                    alarm.setAlarmData(alarmData);
                    alarmList.add(alarm);
                }
            }
        }
        return alarmList;
    }
    public List<Alarm> getNewDataN(Integer project, List<String> StationCodes, Integer DBType) {
        List<Alarm> alarmList = new ArrayList<>();
        List<String> stationCodes = new ArrayList<>();
        List<BDMS_ST_SENSOR_B> bdms_st_sensor_bs = bdms_st_sensor_bService.selectBySTCD29(project, StationCodes);
        for (int i = 0; i < bdms_st_sensor_bs.size(); i++) {
            stationCodes.add(bdms_st_sensor_bs.get(i).getDatacode());
        }
        //获取最新的实测潮位数据
        List<ST_TIDE_R> st_tide_rs = st_tide_rService.selectNewEstData(stationCodes);
        //获取告警状态表
        List<BDMS_ST_SENSORALARM_B> bdms_st_sensoralarm_bs = bdms_st_sensoralarm_bService.selectByStcd(StationCodes, "TDZ", project);


        //站点表
        List<BDMS_ST_STBPRP_B> bdms_st_stbprp_bs = bdms_st_stbprp_bService.selectStationByProject(project);
        for (String stcd : StationCodes) {
            Alarm alarm = new Alarm();
            alarm.setStationCode(stcd);
            //设置站名
            BDMS_ST_SENSOR_B sensor = bdms_st_sensor_bs.stream().filter(BDMS_ST_SENSOR_B -> BDMS_ST_SENSOR_B.getStcd().equals(stcd)).findAny().orElse(null);
            String stationcode = null;
            if (sensor != null) {
                stationcode = sensor.getDatacode();
                BDMS_ST_STBPRP_B bdms_st_stbprp_b = bdms_st_stbprp_bs.stream().filter(BDMS_ST_STBPRP_B -> BDMS_ST_STBPRP_B.getStcd().equals(stcd)).findAny().orElse(null);
                alarm.setStationName(bdms_st_stbprp_b.getStnm());
                AlarmData alarmData = new AlarmData();

                String finalStationcode = stationcode;
                ST_TIDE_R st_tide_r = st_tide_rs.stream().filter(ST_TIDE_R -> ST_TIDE_R.getStcd().equals(finalStationcode)).findAny().orElse(null);
                Data forecastMaxData = new Data();
                Data data = new Data();
                if (st_tide_r != null) {
                    data.setTM(st_tide_r.getTm());
                    data.setValue(st_tide_r.getTdz());
                }
                //设置最新数据
                alarmData.setNewestData(data);
                //获取历史最高潮位
                BDMS_ST_SENSORALARM_B bdms_st_sensoralarm_b = bdms_st_sensoralarm_bs.stream().filter(BDMS_ST_SENSORALARM_Bx ->
                        BDMS_ST_SENSORALARM_Bx.getStcd().equals(stcd)
                ).findAny().orElse(null);

                if (bdms_st_sensoralarm_b != null) {
                    if (bdms_st_sensoralarm_b.getAlarmvalue() != null) {
                        alarmData.setAlarmTideData(String.valueOf(bdms_st_sensoralarm_b.getAlarmvalue()));
                    }
                    if (bdms_st_sensoralarm_b.getHistorymax() != null){
                        alarmData.setAllTimeHighTideLevel(bdms_st_sensoralarm_b.getHistorymax().split(",")[0]);
                    }
                    if (data.getValue() != null) {
                        double alarmValue;
                        if (bdms_st_sensoralarm_b.getAlarmvalue() != null){
                            alarmValue = Double.parseDouble(String.format("%.2f", data.getValue() - bdms_st_sensoralarm_b.getAlarmvalue()));

                            alarmData.setDistanceAlert(String.valueOf(alarmValue));
                            if (alarmValue < -0.5) {
                                //正常
                                alarmData.setAlarmColor("#000000");
                            } else if (alarmValue >= -0.5 && alarmValue <= 0) {
                                //即将超警
                                alarmData.setAlarmColor("#FFBC00");
                            }
                            //                        else if (alarmValue >= -0.2 && alarmValue <= 0) {
                            //                            alarmData.setAlarmColor("#FFA500");
                            //                        }
                            else {
                                //超警
                                alarmData.setAlarmColor("#FF0000");
                            }
                        }else {
                            alarmData.setAlarmColor("#000000");
                        }
                    }
                }
                alarm.setAlarmData(alarmData);
                alarmList.add(alarm);
            }
        }
        return alarmList;
    }

    //根据计算方案id 获取方案信息
    public CalSchemeInfo getCalSchemeInfoByCalSchemeId(String calSchemeId, int DBtype) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.s");
        Calendar calendar = new GregorianCalendar();
        CalSchemeInfo calSchemeInfo = new CalSchemeInfo();
        //新表老表判断
        if (DBtype == 1) { //老表
            BDMS_FBC_RESULT_SCHEME bdms_fbc_result_scheme = null;
            if (calSchemeId == null || calSchemeId.equals("")) {
                bdms_fbc_result_scheme = bdms_fbc_result_schemeService.selectNewOne();
            } else {
                Integer calId = Integer.parseInt(calSchemeId);
                bdms_fbc_result_scheme = bdms_fbc_result_schemeService.selectTimeByCalShemeId(calId);
            }
            if (bdms_fbc_result_scheme != null) {
                calSchemeInfo.setCalSchemeId(String.valueOf(bdms_fbc_result_scheme.getSchemeId()));
                calSchemeInfo.setTyphoonId(String.valueOf(bdms_fbc_result_scheme.getTfid()));
                calSchemeInfo.setForecastTime(bdms_fbc_result_scheme.getYmdhm());
                try {
                    Date ForecastEndTM = format.parse(bdms_fbc_result_scheme.getYmdhm());
                    calendar.setTime(ForecastEndTM);
                    calendar.add(Calendar.HOUR, +bdms_fbc_result_scheme.getCalnum());
                    calSchemeInfo.setForecastEndTime(format.format(calendar.getTime()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                calSchemeInfo.setUserId(String.valueOf(bdms_fbc_result_scheme.getUserId()));
                calSchemeInfo.setModelId(String.valueOf(bdms_fbc_result_scheme.getModelId()));
                calSchemeInfo.setModelPar(String.valueOf(bdms_fbc_result_scheme.getExpparam()));
                calSchemeInfo.setTyphoonDepart(bdms_fbc_result_scheme.getReportDept());
                calSchemeInfo.setState(String.valueOf(bdms_fbc_result_scheme.getState()));

                calSchemeInfo.setRemark("state 0 新建方案、1 计算中、2 计算失败、3 计算成功");

            }

        } else { //新表
            BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m = null;

            if (calSchemeId == null || "".equals(calSchemeId)) {
                bdms_calculatescheme_m = bdms_calculatescheme_mService.selectByNewOne();
            } else {
                bdms_calculatescheme_m = bdms_calculatescheme_mService.selectShcemeByCalID(calSchemeId);
            }


            if (bdms_calculatescheme_m != null) {
                String[] a = bdms_calculatescheme_m.getParams().split(",");
                System.out.println(a[0]);
                calSchemeInfo.setCalSchemeId(bdms_calculatescheme_m.getCschemeid());
                calSchemeInfo.setUserId(bdms_calculatescheme_m.getUserid());
                calSchemeInfo.setTyphoonId(a[0]);
                calSchemeInfo.setTyphoonDepart(a[1]);
                calSchemeInfo.setModelPar(df.format(Double.valueOf(a[2])));
                BDMS_FBC_OCEANMODEL_B bdms_fbc_oceanmodel_b = bdms_fbc_oceanmodel_bService.getModelInfoByModelId(bdms_calculatescheme_m.getPid(), bdms_calculatescheme_m.getMdid());
                if (bdms_fbc_oceanmodel_b != null) {
                    calSchemeInfo.setModelId(bdms_fbc_oceanmodel_b.getModelnm());
                    calSchemeInfo.setModelName(bdms_fbc_oceanmodel_b.getModelnm());

                }

                calSchemeInfo.setForecastOperateTime(bdms_calculatescheme_m.getDtmcalculate());
                calSchemeInfo.setForecastEndTime(bdms_calculatescheme_m.getDtmend());
                calSchemeInfo.setHasGen(bdms_calculatescheme_m.getIsgen());
                calSchemeInfo.setHasArea(bdms_calculatescheme_m.getIsarea());
                calSchemeInfo.setFlag(bdms_calculatescheme_m.getFlag());
                calSchemeInfo.setUserName("预报员");
                calSchemeInfo.setForecastTime(bdms_calculatescheme_m.getDtmforecast());
                calSchemeInfo.setState(String.valueOf(bdms_calculatescheme_m.getState()));
                calSchemeInfo.setRemark("state中 0代表计算方案、1代表计算、2代表计算失败、3代表计算成功");
            }
        }


        return calSchemeInfo;

    }

    //获取预报模型列表
    public List<ModelInfo> getModelInfos(Integer project, List<String> modelTypes) {
        //创建返回对象
        List<ModelInfo> modelInfos = new ArrayList<>();
        //调用方法
        List<BDMS_FBC_OCEANMODEL_B> bdms_fbc_oceanmodel_bs = bdms_fbc_oceanmodel_bService.getModelInfos(project, modelTypes);
        for (BDMS_FBC_OCEANMODEL_B bdms_fbc_oceanmodel_b : bdms_fbc_oceanmodel_bs) {
            ModelInfo modelInfo = new ModelInfo();
            modelInfo.setModelId(bdms_fbc_oceanmodel_b.getModelid());
            modelInfo.setModelName(bdms_fbc_oceanmodel_b.getModelnm());
            modelInfo.setModelAlias(bdms_fbc_oceanmodel_b.getModelabb());
            modelInfo.setModelType(bdms_fbc_oceanmodel_b.getModeltp());
            modelInfo.setModelTypeId(bdms_fbc_oceanmodel_b.getModeltpid());
            modelInfo.setExpectTime("模型预计计算时间为"+bdms_fbc_oceanmodel_b.getExpect()+"秒");
            modelInfos.add(modelInfo);
        }
        return modelInfos;
    }



    //获取海堤前沿计算结果
    public SeaWall getCalResultsBySeaWall(String calSchemeId, Integer seaWallId) throws ParseException {
        //最大返回对象
        SeaWall seaWall = new SeaWall();

        //二级对象
        SeaWallData seaWallData = new SeaWallData();
        seaWallData.setSeaWallId(String.valueOf(seaWallId));
        //List<CalResultGridData> calResultGridDataList = new ArrayList<>();

        //创建集合
        List<ChartData> chartDatas = new ArrayList<>();

        //返回对象
        ChartData zschartData = new ChartData();
        zschartData.setValueName("预报增水");
        zschartData.setCalDataType("zs");
        zschartData.setOrder(1);
        zschartData.setUnit("m");
        ChartData twcchartData = new ChartData();
        twcchartData.setValueName("天文潮");
        twcchartData.setCalDataType("twc");
        twcchartData.setOrder(2);
        twcchartData.setUnit("m");
        ChartData ftdzchartData = new ChartData();
        ftdzchartData.setValueName("预报综合潮位");
        ftdzchartData.setCalDataType("ftdz");
        ftdzchartData.setOrder(3);
        ftdzchartData.setUnit("m");
        //根据计算方案编号获取计算方案
        BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m1 = bdms_calculatescheme_mService.selectShcemeByCalID(calSchemeId);
        //根据计算方案去获取项目id和modelid；
        int projectId = bdms_calculatescheme_m1.getPid();

        //根据海堤编号获取海堤
        BDMS_FBC_SEAWALL_B bdms_fbc_seawall_b = bdms_fbc_seawall_bService.selectBySwid(projectId, seaWallId);
        String seaWallName = bdms_fbc_seawall_b.getSwnm();
        //设置主标题
        String mainheading = "海堤前沿潮位过程图";
        seaWall.setMainHeading(seaWallName + mainheading);
        //模型
        String modelId = bdms_calculatescheme_m1.getMdid();

        //系数    //预报路径
        String params[] = bdms_calculatescheme_m1.getParams().split(",");

        //根据modelid，pid,seaWallId去获取对应格点
        BDMS_FBC_SEAWALL_P bdms_fbc_seawall_p = bdms_fbc_seawall_pService.selectGridBySwid(projectId, seaWallId, modelId);


        //根据获取到的格点去获取潮位数据
        //构造日期函数
//        CalResultGrid calResultGrid = new CalResultGrid();
//        List<CalResultGridData> calResultGridDatas = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = new GregorianCalendar();
        String StartTime = null;
        String EndTime = null;
        try {
            StartTime = bdms_calculatescheme_m1.getDtmforecast();
            EndTime = bdms_calculatescheme_m1.getDtmend();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //根据modelid获取model名称
        BDMS_FBC_OCEANMODEL_B bdms_fbc_oceanmodel_b = bdms_fbc_oceanmodel_bService.getModelInfoByModelId(projectId, modelId);
        double xs = Double.parseDouble(params[2]);
        //设置副标题
        String subheading = "作业预报时间:" + StartTime.substring(0, 19) + " 预报路径:" + params[1] + " 预报模型:" + bdms_fbc_oceanmodel_b.getModelnm() + " 台风系数:" + df.format(xs);
        seaWall.setSubHeading(subheading);
        //根据计算方案编号获取格点数据

        List<CalResultSeaWallData> calResultSeaWallDatas = new ArrayList<>();
        List<String> Grids = Collections.singletonList(bdms_fbc_seawall_p.getCellids());
        for (String grid : Grids) {
            //  List<PointResult> pointResults =new ArrayList<>();

            //过程线
            List<Data> zsDatas = new ArrayList<>();
            List<Data> twcDatas = new ArrayList<>();
            List<Data> ftdzDatas = new ArrayList<>();

            CalResultSeaWallData calResultSeaWallData = new CalResultSeaWallData();
            calResultSeaWallData.setGridId(grid);
//            CalResultGridData calResultGridData  = new CalResultGridData();
//            calResultGridData.setGrid(Integer.valueOf(grid));
            List<BDMS_FBC_ASTROTD_A> bdms_fbc_astrotd_as = bdms_fbc_astrotd_aService.selectByGrid(projectId, StartTime, EndTime, Integer.valueOf(grid));


            List<BDMS_FBC_RESULT_A> bdms_fbc_result_as = bdms_fbc_result_aService.getGridDataBySeaWall(calSchemeId, grid, StartTime, EndTime, 0);
//            for (int i = 0; i < bdms_fbc_result_as.size(); i++) {
//                if (i < bdms_fbc_astrotd_as.size()) {
//                    System.out.println("res"+(bdms_fbc_result_as.get(i).getDttm().equals(bdms_fbc_astrotd_as.get(i).getTm())));
//                    if (bdms_fbc_result_as.get(i).getDttm().equals(bdms_fbc_astrotd_as.get(i).getTm())) {
//                        PointResult pointResult = new PointResult();
//                        Data zsData = new Data();
//                        Data twcData = new Data();
//                        Data ftdzData = new Data();
//                        try {
//                            Date time = format.parse(StartTime);
//                            calendar.setTime(time);
//                            calendar.add(Calendar.HOUR, +i);
//                            pointResult.setTm(format.format(calendar.getTime()));
//                            zsData.setTM(format.format(calendar.getTime()));
//                            twcData.setTM(format.format(calendar.getTime()));
//                            ftdzData.setTM(format.format(calendar.getTime()));
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//
//                        double zs = Double.parseDouble(bdms_fbc_result_as.get(i).getDtvalues());
//                        if (zs == -999) {
//                            zs = 0;
//                        }
//                        zsData.setValue(Double.valueOf(String.format("%.4f", zs / 100)));
//                        pointResult.setZs(Double.valueOf(String.format("%.4f", zs / 100)));
//
//                        Double twc = Double.valueOf(bdms_fbc_astrotd_as.get(i).getDtvalues());
//                        pointResult.setTwc(Double.valueOf(String.format("%.4f", twc)));
//                        twcData.setValue(Double.valueOf(String.format("%.4f", twc)));
//                        Double ftdz = pointResult.getZs() + pointResult.getTwc();
//                        pointResult.setFtdz(Double.valueOf(String.format("%.4f", ftdz)));
//                        ftdzData.setValue(Double.valueOf(String.format("%.4f", ftdz)));
//
//                        zsDatas.add(zsData);
//                        twcDatas.add(twcData);
//                        ftdzDatas.add(ftdzData);
//
//                        //  pointResults.add(pointResult);
//                    }
//                }
//                //   System.out.println(bdms_fbc_result_as.get(i).getDttm().equals(bdms_fbc_astrotd_as.get(i).getTm()));
//
//            }
            for (int i = 0; i < bdms_fbc_astrotd_as.size(); i++) {
                System.out.println(bdms_fbc_astrotd_as.get(i));
                PointResult pointResult = new PointResult();
                Data twcData = new Data();
                Date time = format.parse(StartTime);
                calendar.setTime(time);
                calendar.add(Calendar.HOUR, +i);
                Double twc = Double.valueOf(bdms_fbc_astrotd_as.get(i).getDtvalues());
                pointResult.setTwc(Double.valueOf(String.format("%.4f", twc)));
                twcData.setTM(format.format(calendar.getTime()));
                twcData.setValue(Double.valueOf(String.format("%.4f", twc)));
                pointResult.setTm(format.format(calendar.getTime()));
                if (bdms_fbc_result_as!=null && bdms_fbc_result_as.size()>0) {
                    System.out.println("res"+(bdms_fbc_result_as.get(i).getDttm().equals(bdms_fbc_astrotd_as.get(i).getTm())));
                    if (bdms_fbc_result_as.get(i).getDttm().equals(bdms_fbc_astrotd_as.get(i).getTm())) {
                        Data zsData = new Data();
                        Data ftdzData = new Data();
                        try {
                            zsData.setTM(format.format(calendar.getTime()));
                            twcData.setTM(format.format(calendar.getTime()));
                            ftdzData.setTM(format.format(calendar.getTime()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        double zs = Double.parseDouble(bdms_fbc_result_as.get(i).getDtvalues());
                        if (zs == -999) {
                            zs = 0;
                        }
                        zsData.setValue(Double.valueOf(String.format("%.4f", zs / 100)));
                        pointResult.setZs(Double.valueOf(String.format("%.4f", zs / 100)));



                        Double ftdz = pointResult.getZs() + pointResult.getTwc();
                        pointResult.setFtdz(Double.valueOf(String.format("%.4f", ftdz)));
                        ftdzData.setValue(Double.valueOf(String.format("%.4f", ftdz)));
                        zsDatas.add(zsData);
                        ftdzDatas.add(ftdzData);
                        //  pointResults.add(pointResult);
                    }
                }

                System.out.println(twcData);
                twcDatas.add(twcData);
                //   System.out.println(bdms_fbc_result_as.get(i).getDttm().equals(bdms_fbc_astrotd_as.get(i).getTm()));

            }
            zschartData.setValueDatas(zsDatas);
            twcchartData.setValueDatas(twcDatas);
            ftdzchartData.setValueDatas(ftdzDatas);
            chartDatas.add(zschartData);
            chartDatas.add(twcchartData);
            chartDatas.add(ftdzchartData);
            calResultSeaWallData.setChartDatas(chartDatas);
            calResultSeaWallDatas.add(calResultSeaWallData);
            //    calResultGridData.setPointResults(pointResults);
            //   calResultGridDataList.add(calResultGridData);
        }
        seaWallData.setCalResultSeaWallDatas(calResultSeaWallDatas);
        // seaWallData.setCalResultGridDatas(calResultGridDataList);
        seaWall.setSeaWallData(seaWallData);
        return seaWall;
    }

    public List<SeaWall> getCalResultsBySeaWalls(List<String> calSchemeIds, Integer seaWallId) throws ParseException {
        List<SeaWall> seaWalls = new ArrayList<>();

        for (String calSchemeId : calSchemeIds) {
            //最大返回对象
            SeaWall seaWall = new SeaWall();

            //二级对象
            SeaWallData seaWallData = new SeaWallData();
            seaWallData.setSeaWallId(String.valueOf(seaWallId));
            //List<CalResultGridData> calResultGridDataList = new ArrayList<>();

            //创建集合
            List<ChartData> chartDatas = new ArrayList<>();

            //返回对象
            ChartData zschartData = new ChartData();
            zschartData.setValueName("预报增水");
            zschartData.setCalDataType("zs");
            zschartData.setOrder(1);
            zschartData.setUnit("m");
            ChartData twcchartData = new ChartData();
            twcchartData.setValueName("天文潮");
            twcchartData.setCalDataType("twc");
            twcchartData.setOrder(2);
            twcchartData.setUnit("m");
            ChartData ftdzchartData = new ChartData();
            ftdzchartData.setValueName("预报综合潮位");
            ftdzchartData.setCalDataType("ftdz");
            ftdzchartData.setOrder(3);
            ftdzchartData.setUnit("m");
            //根据计算方案编号获取计算方案
            BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m1 = bdms_calculatescheme_mService.selectShcemeByCalID(calSchemeId);
            seaWall.setCalSchemeName(bdms_calculatescheme_m1.getCschemenm());
            seaWall.setForecastTime(bdms_calculatescheme_m1.getDtmforecast());

            //根据计算方案去获取项目id和modelid；
            int projectId = bdms_calculatescheme_m1.getPid();

            //根据海堤编号获取海堤
            BDMS_FBC_SEAWALL_B bdms_fbc_seawall_b = bdms_fbc_seawall_bService.selectBySwid(projectId, seaWallId);
            String seaWallName = bdms_fbc_seawall_b.getSwnm();
            //设置主标题
            String mainheading = "海堤前沿潮位过程图";
            seaWall.setMainHeading(seaWallName + mainheading);
            //模型
            String modelId = bdms_calculatescheme_m1.getMdid();

            //系数    //预报路径
            String[] params = bdms_calculatescheme_m1.getParams().split(",");
            double xs = Double.parseDouble(params[2]);
            seaWall.setTyphoonDepart((params[1]));
            seaWall.setTyphoonId((params[0]));
            BDMS_FBC_TFINFO_B bdmsFbcTfinfoB = bdms_fbc_tfinfo_bService.queryById(String.valueOf((params[0])));
            seaWall.setTyphoonName(bdmsFbcTfinfoB.getTfnameC());
            seaWall.setModelPar(df.format(xs));

            //根据modelid，pid,seaWallId去获取对应格点
            BDMS_FBC_SEAWALL_P bdms_fbc_seawall_p = bdms_fbc_seawall_pService.selectGridBySwid(projectId, seaWallId, modelId);

            if (bdms_fbc_seawall_p!=null){
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Calendar calendar = new GregorianCalendar();
                String StartTime = null;
                String EndTime = null;


                try {
                    StartTime = bdms_calculatescheme_m1.getDtmforecast();

                    EndTime = bdms_calculatescheme_m1.getDtmend();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                //根据modelid获取model名称
                BDMS_FBC_OCEANMODEL_B bdms_fbc_oceanmodel_b = bdms_fbc_oceanmodel_bService.getModelInfoByModelId(projectId, modelId);
                seaWall.setModelAbb( bdms_fbc_oceanmodel_b.getModelabb());
                Integer dttp =bdms_fbc_oceanmodel_b.getModeltpid();
                int outId =bdms_fbc_oceanmodel_b.getOutstartindexArea();
                seaWall.setModelAbb(bdms_fbc_oceanmodel_b.getModelabb());
                seaWall.setModelName(bdms_fbc_oceanmodel_b.getModelnm());
                seaWall.setCalSchemeAbb(bdms_calculatescheme_m1.getCschemenm()+" "+bdms_calculatescheme_m1.getFschemeid()+" "+seaWall.getModelAbb()+" "+
                        seaWall.getModelPar());
                //设置副标题
                String subheading = null;
                if (StartTime != null) {
                    subheading = "作业预报时间:" + StartTime.substring(0, 19) + " 预报路径:" + params[1] + " 预报模型:" + bdms_fbc_oceanmodel_b.getModelnm() + " 台风系数:" + df.format(xs);
                }
                seaWall.setSubHeading(subheading);
                //根据计算方案编号获取格点数据

                List<CalResultSeaWallData> calResultSeaWallDatas = new ArrayList<>();
                List<String> Grids = Collections.singletonList(bdms_fbc_seawall_p.getCellids());
                for (String grid : Grids) {
                    //  List<PointResult> pointResults =new ArrayList<>();
                    if (grid != null && grid.length() > 0){
                        if ("0".equals(grid)){
                            grid="1";
                        }
                    }
                    //过程线
                    List<Data> zsDatas = new ArrayList<>();
                    List<Data> twcDatas = new ArrayList<>();
                    List<Data> ftdzDatas = new ArrayList<>();

                    CalResultSeaWallData calResultSeaWallData = new CalResultSeaWallData();
                    calResultSeaWallData.setGridId(grid);
//            CalResultGridData calResultGridData  = new CalResultGridData();
//            calResultGridData.setGrid(Integer.valueOf(grid));
                    List<BDMS_FBC_ASTROTD_A> bdms_fbc_astrotd_as = bdms_fbc_astrotd_aService.selectByGrid(projectId, StartTime, EndTime, Integer.valueOf(grid));


                    List<BDMS_FBC_RESULT_A> bdms_fbc_result_as = bdms_fbc_result_aService.getGridDataBySeaWall(calSchemeId, grid, StartTime, EndTime, dttp);


                    if (bdms_fbc_astrotd_as != null) {
                        for (int i = 0; i < bdms_fbc_astrotd_as.size(); i++) {


                                PointResult pointResult = new PointResult();

                                Date time = format.parse(StartTime);
                                calendar.setTime(time);
                                calendar.add(Calendar.HOUR, +i);
                                pointResult.setTm(format.format(calendar.getTime()));
                            if (bdms_fbc_astrotd_as.get(i).getDtvalues()!=null&& !Objects.equals(bdms_fbc_astrotd_as.get(i).getDtvalues(), "")){
                                Double twc = Double.valueOf(bdms_fbc_astrotd_as.get(i).getDtvalues());
                                if (-90<twc && twc<90){

                                    Data twcData = new Data();
                                    twcData.setTM(format.format(calendar.getTime()));
                                    pointResult.setTwc(Double.valueOf(String.format("%.4f", twc)));
                                    twcData.setValue(Double.valueOf(String.format("%.4f", twc)));
                                    twcDatas.add(twcData);
                                }

                            }

                                calendar.setTime(format.parse(bdms_fbc_astrotd_as.get(i).getTm()));
                                calendar.add(Calendar.HOUR,+outId);
                                String t = format.format(calendar.getTime());
                                if (bdms_fbc_result_as!=null&&bdms_fbc_result_as.size()>0){
                                    if (i<bdms_fbc_result_as.size()) {
                                        if (bdms_fbc_result_as.get(i).getDttm().equals(t)) {

                                            Data zsData = new Data();

                                            Data ftdzData = new Data();
                                            try {
//                                        Date time = format.parse(StartTime);
//                                        calendar.setTime(time);
//                                        calendar.add(Calendar.HOUR, +i);
                                                pointResult.setTm(format.format(calendar.getTime()));
                                                zsData.setTM(format.format(calendar.getTime()));
                                                //twcData.setTM(format.format(calendar.getTime()));
                                                ftdzData.setTM(format.format(calendar.getTime()));
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }

                                            double zs = Double.parseDouble(bdms_fbc_result_as.get(i).getDtvalues());

                                            if (zs == -9990.0) {
                                                zs = 0;
                                            }
                                            zsData.setValue(Double.valueOf(String.format("%.4f", zs / 100)));
                                            pointResult.setZs(Double.valueOf(String.format("%.4f", zs / 100)));


//                                            pointResult.setTwc(Double.valueOf(String.format("%.4f", twc)));
//                                            twcData.setValue(Double.valueOf(String.format("%.4f", twc)));

                                            Double ftdz  =null;
                                            if (pointResult.getTwc()!=null){
                                                 ftdz  = pointResult.getZs() + pointResult.getTwc();

                                            }else {
                                                ftdz  = pointResult.getZs() ;
                                            }


                                            pointResult.setFtdz(Double.valueOf(String.format("%.4f", ftdz)));
                                            ftdzData.setValue(Double.valueOf(String.format("%.4f", ftdz)));
                                            zsDatas.add(zsData);
                                            //twcDatas.add(twcData);
                                            ftdzDatas.add(ftdzData);

                                            //  pointResults.add(pointResult);
                                        }
                                    }
                                }




                            //   System.out.println(bdms_fbc_result_as.get(i).getDttm().equals(bdms_fbc_astrotd_as.get(i).getTm()));

                        }

                    }
                    zschartData.setValueDatas(zsDatas);
                    twcchartData.setValueDatas(twcDatas);
                    ftdzchartData.setValueDatas(ftdzDatas);
                    chartDatas.add(zschartData);
                    chartDatas.add(twcchartData);
                    chartDatas.add(ftdzchartData);
                    calResultSeaWallData.setChartDatas(chartDatas);
                    calResultSeaWallDatas.add(calResultSeaWallData);
                    //    calResultGridData.setPointResults(pointResults);
                    //   calResultGridDataList.add(calResultGridData);
                }
                seaWallData.setCalResultSeaWallDatas(calResultSeaWallDatas);
                // seaWallData.setCalResultGridDatas(calResultGridDataList);
                seaWall.setSeaWallData(seaWallData);
                seaWalls.add(seaWall);
            }

        }

        return seaWalls;
    }

    //获取预报站点特征值GetCharacteristicByStation
    public List<Characteristic> getCharacteristicByStation(String calSchemeId, List<String> stationCodes) throws IOException, ParseException {
        List<Characteristic> characteristics = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = new GregorianCalendar();
        //根据方案编号获取方案
        BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m = bdms_calculatescheme_mService.selectShcemeByCalID(calSchemeId);
        //根据方案编号获取预报数据
        int pid = bdms_calculatescheme_m.getPid();
        List<BDMS_FBC_RESULT_P> bdms_fbc_results = bdms_fbc_result_pService.selecTBySchemeId(calSchemeId, stationCodes);
        List<String> stcds = new ArrayList<>();
        for (BDMS_FBC_RESULT_P bdms_fbc_result : bdms_fbc_results) {
            stcds.add(bdms_fbc_result.getPtkey());
        }
        List<String> cals = new ArrayList<>();
        cals.add(calSchemeId);
        List<BDMS_ST_SENSORALARM_B> bdms_st_sensoralarm_bs = bdms_st_sensoralarm_bService.selectByStcd(stationCodes, "TDZ", pid);

        //循环站点
        for (String stationCode : stationCodes) {
            Characteristic characteristic = new Characteristic();
            //调用获取预报站点结果方法
            com.jhhc.utils.CalResult calResult = getDataUtil.getDataByCalSchemeIds(pid, cals, stationCode, 0, 0, 60, 0);
            com.jhhc.utils.ChartData chartData = calResult.getCalSchemeInfos().get(0).getResults().stream().filter(chartData1 -> "ftdz".equals(chartData1.getSensorType())).findAny().orElse(null);
            if (chartData != null) {
                //获取预报潮位的最大值
                Data data = chartData.getMaxData();
                characteristic.setStationCode(stationCode);
                characteristic.setForecastMaximumTide(String.valueOf(data.getValue()));
                characteristic.setPredictionOfTide(data.getTM());

                BDMS_ST_SENSORALARM_B bdms_st_sensoralarm_b = bdms_st_sensoralarm_bs.stream().filter(BDMS_ST_SENSORALARM_Bx ->
                        BDMS_ST_SENSORALARM_Bx.getStcd().equals(stationCode)
                ).findAny().orElse(null);

                if (bdms_st_sensoralarm_b != null) {
                    if (data.getValue() != null && bdms_st_sensoralarm_b.getAlarmvalue()!=null) {
                        double alarmValue;
                        if (bdms_st_sensoralarm_b.getAlarmvalue() != null) {
                            alarmValue = Double.parseDouble(String.format("%.2f", data.getValue() - bdms_st_sensoralarm_b.getAlarmvalue()));
                        }else {
                            alarmValue = Double.parseDouble(String.format("%.2f", data.getValue()));
                        }
                        characteristic.setDistanceAlert(String.valueOf(alarmValue));
                        if (alarmValue < -0.5) {
                            //正常
                            characteristic.setState("#000000");
                        } else if (alarmValue >= -0.5 && alarmValue <= 0) {
                            //即将超警
                            characteristic.setState("#FFBC00");
                        }
//                        else if (alarmValue >= -0.2 && alarmValue <= 0) {
//                            alarmData.setAlarmColor("#FFA500");
//                        }
                        else {
                            //超警
                            characteristic.setState("#FF0000");
                        }

                    }


                }

            }
            characteristics.add(characteristic);
        }



//        String StartTime = null;
//        String EndTime = null;
//        //预报增水
//        String startTime = null;
//        //查询预报增水值
//        //获取预报方案  新表
//        Integer typhoonId = null;
//        String Forecasttime = null;
//        List<BDMS_CALCULATESCHEME_M1> bdms_fbc_result_schemes = bdms_calculatescheme_mService.selectShcemeByPidCalID(pid, calSchemeId);
//        System.out.println(bdms_fbc_result_schemes);
//        String param = bdms_fbc_result_schemes.get(0).getParams();
//        String[] params = param.split(",");
//        typhoonId = Integer.valueOf(params[0]);
//        BDMS_FBC_TFINFO_B bdmsFbcTfinfoB = bdms_fbc_tfinfo_bService.queryById(String.valueOf(typhoonId));
//        List<BDMS_ST_SENSORALARM_B> bdms_st_sensoralarm_bs = bdms_st_sensoralarm_bService.selectByStcd(stationCodes, "TDZ", pid);
//
//        for (BDMS_CALCULATESCHEME_M1 bdms_fbc_result_scheme : bdms_fbc_result_schemes) {
//            StartTime = bdms_fbc_result_scheme.getDtmforecast();
//            startTime = StartTime;
//            EndTime = bdms_fbc_result_scheme.getDtmend();
//
//        }
//        //两个条件
//        //获取天文超数据
//        List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFList = bdms_st_astrotd_fService.selectFTDZ(stationCodes, startTime, EndTime, 0);
//        //获取高低潮
//        //构造比较日期
//        String TdzTime;
//        String FtdzTime;
//        String DataTime;
//        //获取到实测和天文潮后构造 PointResult
//        //Listdata
//        List<Data> dataList = new ArrayList<>();
//
//        if (bdmsStAstrotdFList.size() > 0) {
//            for (String stcd : stationCodes) {
//                Characteristic characteristic = new Characteristic();
//                List<PointResult> pointResults = new ArrayList<>();
//                List<PointResult> pointHLResults = new ArrayList<>();
//                //构造返回对象
//                CalResult calResult = new CalResult();
//                //设置站码
//
//                List<BDMS_FBC_RESULT_P> bdms_fbc_resultsList = bdms_fbc_results.stream().filter(BDMS_FBC_RESULT -> BDMS_FBC_RESULT.getPtkey().equals(stcd)).collect(Collectors.toList());
//                //获取值
//                for (BDMS_FBC_RESULT_P bdms_fbc_result : bdms_fbc_resultsList) {
//                    data_all(bdms_fbc_result.getDtvalues());
//                }
//                //获取values平均值
//                Double avg;
//                if (values != null) {
//                    for (int i = 0; i < values.size(); i++) {
//                        try {
//                            Date date = format.parse(StartTime);
//                            calendar.setTime(date);
//                            calendar.add(Calendar.HOUR, +i);
//                            dataList.add(new Data(format.format(calendar.getTime()), values.get(i)));
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//                dataList.sort(Comparator.comparing(Data::getTM));
//                //站码  分组
//                System.out.println("增水："+dataList);
//                List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFs = bdmsStAstrotdFList.stream().filter(BDMS_ST_ASTROTD_F -> BDMS_ST_ASTROTD_F.getStcd().equals(stcd)).collect(Collectors.toList());
//                for (BDMS_ST_ASTROTD_F bdmsStAstrotdF : bdmsStAstrotdFs) {
//                    FtdzTime = bdmsStAstrotdF.getYmdh();
//                    for (Data data : dataList) {
//                        DataTime = data.getTM();
//                        if (bdmsStAstrotdF.getFtdz() != null) {
//                            //设置高低潮
//                            if (bdmsStAstrotdF.getHltdmk() != null && bdmsStAstrotdF.getHltdmk() > 0) {
//                                //
//                                PointResult pointHLResult = new PointResult();
//                                pointHLResult.setTm(bdmsStAstrotdF.getYmdh());
//                                //System.out.println(pointHLResult.getTm()+"hlp");
//                                pointHLResult.setTwc(bdmsStAstrotdF.getFtdz());
//                                pointHLResults.add(pointHLResult);
//                            } else {
//                                //设置天文潮预报对象
//                                PointResult pointResult = new PointResult();
//                                pointResult.setTm(bdmsStAstrotdF.getYmdh());
//                                pointResult.setTwc(bdmsStAstrotdF.getFtdz());
//                                String TM = FtdzTime;
//
//                                Data datas = dataList.stream().filter(Data -> Data.getTM().equals(TM)).findAny().orElse(null);
//                                if (datas != null) {
//                                    if (datas.getTM().equals(FtdzTime)) {
//                                        pointResult.setTm(datas.getTM());
//                                        // System.out.println(pointResult.getTm()+"p");
//                                        pointResult.setZs(datas.getValue());
//                                        double a = pointResult.getZs();
//                                        double b = bdmsStAstrotdF.getFtdz();
//                                        float a1 = (float) a;
//                                        float b1 = (float) b;
//                                        pointResult.setFtdz(Double.parseDouble(String.format("%.2f", a1 + b1)));
//                                    }
//                                }
//                                //特征值集合
//                                pointResults.add(pointResult);
//                                break;
//                            }
//                            break;
//                        }
//                        continue;
//                    }
//                    // break;
//                }
//                //gouzao    PointHLResults 作业预报开始时间 结束之间 范围的数据  List  gouzao
//                //判断
//                try {
//                    calendar.setTime(format.parse(StartTime));
//                    calendar.add(Calendar.HOUR, -1);
//                    Date start = calendar.getTime();
//                    calendar.setTime(format.parse(EndTime));
//                    calendar.add(Calendar.HOUR, -1);
//                    Date end = calendar.getTime();
//                    List<PointResult> pointResults1 = pointResults.stream().filter(
//                            PointResult -> {
//                                try {
//                                    return format.parse(PointResult.getTm()).after(start)
//                                            && format.parse(PointResult.getTm()).before(end);
//                                } catch (ParseException e) {
//                                    e.printStackTrace();
//                                }
//                                return false;
//                            }).collect(Collectors.toList());
//                    List<PointResult> pointHLResults1 = pointHLResults.stream().filter(
//                            PointResult -> {
//                                try {
//                                    return start.before(format.parse(PointResult.getTm())) &&
//                                            start.before(format.parse(PointResult.getTm()));
//                                } catch (ParseException e) {
//                                    e.printStackTrace();
//                                }
//                                return false;
//                            }).collect(Collectors.toList());
//                    //   List<PointResult> pointHLResults2 = new ArrayList<>();
//                    for (int i = 0; i < pointHLResults1.size(); i++) {
//                        PointResult pointHLResult = new PointResult();
//                        String pointHLResultsYear = pointHLResults1.get(i).getTm().substring(0, 16);
//                        boolean res = Integer.parseInt(pointHLResultsYear.substring(14, 16)) >= 30;
//                        String time = pointHLResultsYear.substring(0, 13) + ":00:00.0";
//                        Date Time = format.parse(time);
//                        calendar.setTime(Time);
//                        if (res) {
//                            calendar.add(Calendar.HOUR, +1);
//                        }
//                        String day = format.format(calendar.getTime());
//                        //根据日期去获取对应的逐时
//                        PointResult pointResult = pointResults1.stream().filter(PointResult -> PointResult.getTm().equals(day)).findAny().orElse(null);
//                        if (pointResult != null) {
//                            pointHLResult.setTm(pointHLResults1.get(i).getTm());
//                            String tm = pointHLResult.getTm();
//                            pointHLResult.setZs(pointResult.getZs());
//                            pointHLResult.setTwc(pointHLResults1.get(i).getTwc());
//                            pointHLResult.setFtdz(pointHLResult.getZs() + pointHLResult.getTwc());
//                            for (PointResult pointHLs : pointHLResults) {
//                                if (pointHLs.getTm().equals(tm)) {
//                                    pointHLs.setTm(tm);
//                                    pointHLs.setTwc(pointHLResult.getTwc());
//                                    pointHLs.setZs(pointHLResult.getZs());
//                                    pointHLs.setFtdz(pointHLs.getZs() + pointHLs.getTwc());
//                                }
//                            }
//                        }
//                    }
//                    calResult.setPointResults(pointResults);
//                    calResult.setPointHLResults(pointHLResults);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                List<PointResult> pointResultsFtdz = calResult.getPointResults().stream().filter(PointResult -> PointResult.getFtdz() != null).collect(Collectors.toList());
//                PointResult poFtzd = pointResultsFtdz.stream().max(Comparator.comparing(PointResult::getFtdz)).orElse(null);
//                List<PointResult> pointResultsFtdz1 = calResult.getPointHLResults().stream().filter(PointResult -> PointResult.getFtdz() != null).collect(Collectors.toList());
//                PointResult poFtzd1 = pointResultsFtdz1.stream().max(Comparator.comparing(PointResult::getFtdz)).orElse(null);
//                if (poFtzd != null) {
//                    calResult.setMaxFtdzTm(poFtzd.getTm());
//                    calResult.setMaxFtdz(poFtzd.getFtdz());
//                }
//                BDMS_ST_SENSORALARM_B bdms_st_sensoralarm_b = bdms_st_sensoralarm_bs.stream().filter(BDMS_ST_SENSORALARM_B -> BDMS_ST_SENSORALARM_B.getStcd().equals(stcd)).findAny().orElse(null);
//                Double value = null;
//                if (bdms_st_sensoralarm_b != null) {
//                    value = bdms_st_sensoralarm_b.getAlarmvalue();
//                }
//                if (poFtzd != null) {
//                    if ((value != null && poFtzd.getFtdz() != null) && value < poFtzd.getFtdz()) {
//
//                        characteristic.setDistanceAlert(String.format("%.2f", poFtzd.getFtdz() - value));
//                        if (Math.abs(value - poFtzd.getFtdz()) >= 0.5 && Math.abs(value - poFtzd.getFtdz()) < 1) {
//                            characteristic.setState("黄色预警");
//                        } else if (Math.abs(value - poFtzd.getFtdz()) >= 1 && Math.abs(value - poFtzd.getFtdz()) < 1.5) {
//                            characteristic.setState("橙色预警");
//                        } else if (Math.abs(value - poFtzd.getFtdz()) >= 1.5) {
//                            characteristic.setState("红色预警");
//                        }
//                    } else {
//                        if (value!=null) {
//                            characteristic.setDistanceAlert(String.format("%.2f", poFtzd.getFtdz() - value));
//                            characteristic.setState("正常");
//                        }
//                    }
//                }
//
//                characteristic.setStationCode(stcd);
//                if (poFtzd != null) {
//                    characteristic.setPredictionOfTide(poFtzd.getTm());
//                    characteristic.setForecastMaximumTide(String.valueOf(poFtzd.getFtdz()));
//                }
//
//
//                characteristics.add(characteristic);
//            }
//
//        }
        return characteristics;
    }


    ////GetCharacteristicBySeaWall 获取海堤前沿特征数据
    public List<Characteristic> getCharacteristicBySeaWall(String calSchemeId, List<Integer> seaWallIds) {

        //最大返回对象
        List<Characteristic> characteristics = new ArrayList<>();
        //根据计算方案编号获取项目id
        //根据计算方案编号获取计算方案
        BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m1 = bdms_calculatescheme_mService.selectShcemeByCalID(calSchemeId);
        //根据计算方案去获取项目id和modelid；
        int projectId = bdms_calculatescheme_m1.getPid();
        String modelId = bdms_calculatescheme_m1.getMdid();
        //获取预报开始和结束时间
        String StartTime = bdms_calculatescheme_m1.getDtmforecast();
        String EndTime = bdms_calculatescheme_m1.getDtmend();
        //根据计算方案编号获取海堤编号
        //默认查询所有海堤
        //获取海堤编号
        List<Integer> swids = new ArrayList<>();
        List<BDMS_FBC_SEAWALL_B> bdms_fbc_seawall_bs = bdms_fbc_seawall_bService.selectByPidSwids(projectId, seaWallIds);
        for (BDMS_FBC_SEAWALL_B bdms_fbc_seawall_b : bdms_fbc_seawall_bs) {
            swids.add(bdms_fbc_seawall_b.getSwid());
        }

        //获取格点编号
        List<BDMS_FBC_SEAWALL_P> bdms_fbc_seawall_ps = bdms_fbc_seawall_pService.selectGridByPidSwids1(projectId, swids, modelId);
        //List<BDMS_ST_SENSORALARM_B> bdms_st_sensoralarm_bs = bdms_st_sensoralarm_bService.selectByStcd(stationCodes,"TDZ",pid);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = new GregorianCalendar();
        //根据获取到的海堤编号  和 格点编号去获取数据
        for (BDMS_FBC_SEAWALL_P bdms_fbc_seawall_p : bdms_fbc_seawall_ps) {
            Characteristic characteristic = new Characteristic();
            characteristic.setSeaWallID(String.valueOf(bdms_fbc_seawall_p.getSwid()));
            List<PointResult> pointResults = new ArrayList<>();
            List<BDMS_FBC_ASTROTD_A> bdms_fbc_astrotd_as = bdms_fbc_astrotd_aService.selectByGrid(projectId, StartTime, EndTime, Integer.valueOf(bdms_fbc_seawall_p.getCellids()));
            List<BDMS_FBC_RESULT_A> bdms_fbc_result_as = bdms_fbc_result_aService.getGridDataBySeaWall(calSchemeId, bdms_fbc_seawall_p.getCellids(), StartTime, EndTime, 2);
            for (int i = 0; i < bdms_fbc_result_as.size(); i++) {
                if (i < bdms_fbc_astrotd_as.size()) {
                    if (bdms_fbc_result_as.get(i).getDttm().equals(bdms_fbc_astrotd_as.get(i).getTm())) {
                        PointResult pointResult = new PointResult();
                        Data ftdzData = new Data();
                        try {
                            Date time = format.parse(StartTime);
                            calendar.setTime(time);
                            calendar.add(Calendar.HOUR, +i);
                            pointResult.setTm(format.format(calendar.getTime()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        double zs;
                        if (Double.parseDouble(bdms_fbc_result_as.get(i).getDtvalues().replaceAll(",",""))<-99){
                            zs = 0.00;
                        }else {
                             zs = Double.parseDouble(bdms_fbc_result_as.get(i).getDtvalues().replaceAll(",",""));
                        }
                        pointResult.setZs(Double.valueOf(String.format("%.2f", zs / 100)));
                        Double twc = Double.valueOf(bdms_fbc_astrotd_as.get(i).getDtvalues());
                        pointResult.setTwc(Double.valueOf(String.format("%.2f", twc)));
                        Double ftdz = pointResult.getZs() + pointResult.getTwc();
                        pointResult.setFtdz(Double.valueOf(String.format("%.2f", ftdz)));
                        pointResults.add(pointResult);
                        pointResults.add(pointResult);
                    }
                }

            }


            PointResult pointResult = pointResults.stream().max(Comparator.comparing(PointResult::getFtdz)).orElse(null);
            if (pointResult != null) {
                Double value = pointResult.getFtdz();
                String time = pointResult.getTm();

                //获取起点高程
                BDMS_FBC_SEAWALL_B bdms_fbc_seawall_b = bdms_fbc_seawall_bs.stream().filter(BDMS_FBC_SEAWALL_B -> BDMS_FBC_SEAWALL_B.getSwid().equals(bdms_fbc_seawall_p.getSwid())).findAny().orElse(null);
                Double avgbankh = (bdms_fbc_seawall_b.getBankhMax() + bdms_fbc_seawall_b.getBankhMin()) / 2;
                Double avg = Double.valueOf(String.format("%.2f", avgbankh));
                if (value > avg) {
                    characteristic.setDistanceAlert(String.format("%.2f", Math.abs(value - avg)));
                    if (Math.abs(value - avg) > 0 && Math.abs(value - avg) < 1) {
                        characteristic.setState("黄色预警");
                    } else if (Math.abs(value - avg) >= 1 && Math.abs(value - avg) < 1.5) {
                        characteristic.setState("橙色预警");
                    } else if (Math.abs(value - avg) >= 1.5) {
                        characteristic.setState("红色预警");
                    }
                } else {
                    characteristic.setDistanceAlert(String.format("%.2f", Math.abs(avg - value)));
                    characteristic.setState("正常");
                }
                characteristic.setForecastMaximumTide(String.valueOf(value));
                characteristics.add(characteristic);
                characteristic.setPredictionOfTide(time);
            }
        }
        return characteristics;


    }

    //获取预报精度评定结果
    //获取预报结果
    public List<ForecastDifference> getForecastDifference(List<String> calSchemeIds) throws IOException, ParseException {
        //构造日期函数
        // 日期格式转换
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = new GregorianCalendar();
        List<ForecastDifference> list = new ArrayList<>();




        for (String calSchemeId : calSchemeIds) {
            ForecastDifference forecastDifference = new ForecastDifference();
            forecastDifference.setCalSchemeId(calSchemeId);
            //构造返回对象
            List<AccuracyEvaluationResult> accuracyEvaluationResults = new ArrayList<>();
            List<AccuracyEvaluationResult> accuracyPorkResults = new ArrayList<>();
            //根据计算方案编号 获取站码
            BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m = bdms_calculatescheme_mService.selectShcemeByCalID(calSchemeId);
            int projectId = bdms_calculatescheme_m.getPid();
            //获取pid 下所有的站码
            List<BDMS_ST_SENSOR_B> bdms_st_sensor_bs = bdms_st_sensor_bService.queryDisnetStcd(projectId);
            //获取天文潮 取数码
            List<String> tdzDatacode = new ArrayList<>();
            List<String> ftdzDatacode = new ArrayList<>();
            for (BDMS_ST_SENSOR_B bdms_st_sensor_b : bdms_st_sensor_bs) {
                if (bdms_st_sensor_b.getSensororder() == 1) {
                    tdzDatacode.add(bdms_st_sensor_b.getDatacode());
                } else {
                    ftdzDatacode.add(bdms_st_sensor_b.getDatacode());
                }
            }
            List<String> cals = new ArrayList<>();
            cals.add(calSchemeId);
            //循环所有的实 测站点
            for (String datacode : ftdzDatacode) {
                //定义返回参数
                AccuracyEvaluationResult accuracyEvaluationResult = new AccuracyEvaluationResult();
                AccuracyEvaluationResult accuracyPeakResult = new AccuracyEvaluationResult();
                List<AccuracyEvaluation> accuracyEvaluations = new ArrayList<>();
                List<AccuracyEvaluation> accuracyPeaks = new ArrayList<>();
                AccuracyEvaluation tenAccuracyEvaluation = new AccuracyEvaluation();
                AccuracyEvaluation twAccuracyEvaluation = new AccuracyEvaluation();
                AccuracyEvaluation thAccuracyEvaluation = new AccuracyEvaluation();
                AccuracyEvaluation forAccuracyEvaluation = new AccuracyEvaluation();
                AccuracyEvaluation tenAccuracyEvaluationf = new AccuracyEvaluation();
                AccuracyEvaluation twAccuracyEvaluationf = new AccuracyEvaluation();
                AccuracyEvaluation thAccuracyEvaluationf = new AccuracyEvaluation();
                AccuracyEvaluation forAccuracyEvaluationf = new AccuracyEvaluation();
                accuracyEvaluationResult.setStationCode(datacode);
                accuracyPeakResult.setStationCode(datacode);
                accuracyEvaluationResult.setStationName(bdms_st_sensor_bs.stream().filter(bdms_st_sensor_b1 -> bdms_st_sensor_b1.getStcd().equals(datacode)).findAny().get().getStnm());
                accuracyPeakResult.setStationName(bdms_st_sensor_bs.stream().filter(bdms_st_sensor_b1 -> bdms_st_sensor_b1.getStcd().equals(datacode)).findAny().get().getStnm());

                int ten = 0;
                int twenty = 0;
                int thirty = 0;
                int forty = 0;
               com.jhhc.utils.CalResult calResult = getDataUtil.getDataByCalSchemeIds(projectId,cals,datacode,0,0,60,0);

               //获取实测数据
              com.jhhc.utils.ChartData chartDataT = calResult.getBaseDatas().stream().filter(chartData -> chartData.getSensorType().equals("tdz")).findAny().orElse(null);

              //预报数据
                com.jhhc.utils.ChartData chartDataF = calResult.getCalSchemeInfos().get(0).getResults().stream().filter(chartData -> chartData.getSensorType().equals("ftdz")).findAny().orElse(null);

                //实测减去预报数据
                //确定预报数据条数
                int res = 0;
                if (chartDataF != null && chartDataT !=null) {
                    res = chartDataF.getDatas().size();
                    for (Data data : chartDataF.getDatas())  {
                        System.out.println(chartDataT);
                        Data dataT =  chartDataT.getDatas().stream().filter(data1 -> data1.getTM().equals(data.getTM())).findAny().orElse(null);
                        if (dataT != null) {
                            double zs =0.0;
                            if (dataT.getValue()<0&&data.getValue()<0){
                                zs =(Math.abs(dataT.getValue()) -Math.abs(data.getValue()))* 100;
                            }else {
                                zs = (dataT.getValue() - data.getValue())* 100;
                            }

                            if (Math.abs(zs) < 10) {
                                ten++;
                            } else if (Math.abs(zs) < 20) {
                                twenty++;
                            } else if (Math.abs(zs) < 30) {
                                thirty++;
                            } else if (Math.abs(zs) >= 30) {
                                forty++;
                            }
//                        System.out.println(dataT.getValue());
//                        System.out.println(data.getValue());
//                        System.out.println(zs);
//                        System.out.println("===============");
                        }


                    }
                    tenAccuracyEvaluation.setStandardRange("<±10cm");
                    double d = (double) (ten) / res;
                    Statistics processStatistics = new Statistics();
                    processStatistics.setQualifiedNumber(ten + "/" + res);
                    processStatistics.setQualifiedRate(Math.round(d * 100) + "%");
                    tenAccuracyEvaluation.setProcessResult(processStatistics);
                    accuracyEvaluations.add(tenAccuracyEvaluation);

                    twAccuracyEvaluation.setStandardRange("<±20cm");
                    double d2 = (double) (ten + twenty) / res;
                    Statistics twprocessStatistics = new Statistics();
                    twprocessStatistics.setQualifiedNumber((ten + twenty) + "/" + res);
                    twprocessStatistics.setQualifiedRate(Math.round(d2 * 100) + "%");
                    twAccuracyEvaluation.setProcessResult(twprocessStatistics);
                    accuracyEvaluations.add(twAccuracyEvaluation);

                    thAccuracyEvaluation.setStandardRange("<±30cm");
                    double d3 = (double) (ten + twenty + thirty) / res;
                    Statistics thprocessStatistics = new Statistics();
                    thprocessStatistics.setQualifiedNumber((ten + twenty + thirty) + "/" + res);
                    thprocessStatistics.setQualifiedRate((Math.round(d3 * 100)) + "%");
                    thAccuracyEvaluation.setProcessResult(thprocessStatistics);
                    accuracyEvaluations.add(thAccuracyEvaluation);

                    forAccuracyEvaluation.setStandardRange("≥±30cm");
                    double d4 = (double) (forty) / res;
                    Statistics foprocessStatistics = new Statistics();
                    foprocessStatistics.setQualifiedNumber((forty) + "/" + res);
                    foprocessStatistics.setQualifiedRate(Math.round(d4 * 100) + "%");
                    forAccuracyEvaluation.setProcessResult(foprocessStatistics);
                    accuracyEvaluations.add(forAccuracyEvaluation);

                    accuracyEvaluationResult.setAccuracyEvaluations(accuracyEvaluations);
                    accuracyEvaluationResults.add(accuracyEvaluationResult);
                }

                //峰值
//                tenAccuracyEvaluationf.setStandardRange("<±10cm");
//               // double df = (double) ten_f / res;
//
//                Statistics processStatisticsf = new Statistics();
//                processStatisticsf.setQualifiedNumber(ten + "/" + res);
//                processStatisticsf.setQualifiedRate(Math.round(df * 100) + "%");
//                tenAccuracyEvaluationf.setProcessResult(processStatisticsf);
//                accuracyPeaks.add(tenAccuracyEvaluationf);
//
//                twAccuracyEvaluationf.setStandardRange("<±20cm");
//                double d2f = (double) twenty_f / res;
//                // System.out.println(d2f);
//                Statistics twprocessStatisticsf = new Statistics();
//                twprocessStatisticsf.setQualifiedNumber(twenty_f + "/" + res);
//                twprocessStatisticsf.setQualifiedRate(Math.round(d2f * 100) + "%");
//                twAccuracyEvaluation.setProcessResult(twprocessStatisticsf);
//                accuracyPeaks.add(twAccuracyEvaluationf);
//
//                thAccuracyEvaluationf.setStandardRange("<±30cm");
//                double d3f = (double) (thirty_f) / res;
//                Statistics thprocessStatisticsf = new Statistics();
//                thprocessStatisticsf.setQualifiedNumber((thirty_f) + "/" + res);
//                thprocessStatisticsf.setQualifiedRate((Math.round(d3f * 100)) + "%");
//                thAccuracyEvaluationf.setProcessResult(thprocessStatisticsf);
//                accuracyPeaks.add(thAccuracyEvaluationf);
//
//                forAccuracyEvaluationf.setStandardRange("≥±30cm");
//                double d4f = (double) (forty_f) / res;
//                Statistics foprocessStatisticsf = new Statistics();
//                foprocessStatisticsf.setQualifiedNumber((forty_f) + "/" + res);
//                foprocessStatisticsf.setQualifiedRate(Math.round(d4f * 100) + "%");
//                forAccuracyEvaluationf.setProcessResult(foprocessStatisticsf);
//                accuracyPeaks.add(forAccuracyEvaluationf);
//
//                accuracyPeakResult.setAccuracyPeaks(accuracyPeaks);
//                accuracyPorkResults.add(accuracyPeakResult);


                //

            }





//            List<BDMS_FBC_RESULT_P> bdms_fbc_results = bdms_fbc_result_pService.selecTBySchemeId(calSchemeId, ftdzDatacode);
//            String StartTime = null;
//            String EndTime = null;
//            //预报增水
//            String startTime = null;
//            //查询预报增水值
//            //获取预报方案  新表
//            Integer typhoonId = null;
//            String Forecasttime = null;
//            List<BDMS_CALCULATESCHEME_M1> bdms_fbc_result_schemes = bdms_calculatescheme_mService.selectShcemeByPidCalID(projectId, calSchemeId);
//
//            String param = bdms_fbc_result_schemes.get(0).getParams();
//            String[] params = param.split(",");
//            typhoonId = Integer.valueOf(params[0]);
//            BDMS_FBC_TFINFO_B bdmsFbcTfinfoB = bdms_fbc_tfinfo_bService.queryById(String.valueOf(typhoonId));
//
//            for (BDMS_CALCULATESCHEME_M1 bdms_fbc_result_scheme : bdms_fbc_result_schemes) {
//                StartTime = bdms_fbc_result_scheme.getDtmforecast();
//                Forecasttime = bdms_fbc_result_scheme.getDtmforecast();
//                try {
//                    calendar.setTime(format.parse(StartTime));
//                    calendar.add(Calendar.DATE, -0);
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }
//                startTime = format.format(calendar.getTime());
//                EndTime = bdms_fbc_result_scheme.getDtmend();
//
//            }
//            //获取到站码集合后，去调用获取实测和天文潮数据
//            //获取实测
//            List<ST_TIDE_R> st_tide_rList = st_tide_rService.selectByStcd(tdzDatacode, startTime, EndTime);
//            String min = "00";
//            //两个条件
//            //获取天文超数据
//            List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFList = bdms_st_astrotd_fService.selectFTDZ(ftdzDatacode, startTime, EndTime, 0);
//            //获取高低潮
//            //构造比较日期
//            String TdzTime;
//            String FtdzTime;
//            String DataTime;
//
//            //Listdata
//            if (bdmsStAstrotdFList.size() > 0) {
//                for (String stcd : ftdzDatacode) {
//                    AccuracyEvaluationResult accuracyEvaluationResult = new AccuracyEvaluationResult();
//                    AccuracyEvaluationResult accuracyPeakResult = new AccuracyEvaluationResult();
//                    List<PointResult> pointResults = new ArrayList<>();
//                    List<AccuracyEvaluation> accuracyEvaluations = new ArrayList<>();
//                    List<AccuracyEvaluation> accuracyPeaks = new ArrayList<>();
//                    List<PointResult> pointHLResults = new ArrayList<>();
//                    List<Data> dataList = new ArrayList<>();
//                    //预报精度评定
//                    int ten = 0;
//                    int ten_t = 0;
//                    int twenty = 0;
//                    int twenty_t = 0;
//                    int thirty = 0;
//                    int thirty_t = 0;
//                    int forty = 0;
//                    int forty_t = 0;
//                    AccuracyEvaluation tenAccuracyEvaluation = new AccuracyEvaluation();
//                    AccuracyEvaluation twAccuracyEvaluation = new AccuracyEvaluation();
//                    AccuracyEvaluation thAccuracyEvaluation = new AccuracyEvaluation();
//                    AccuracyEvaluation forAccuracyEvaluation = new AccuracyEvaluation();
//                    AccuracyEvaluation tenAccuracyEvaluationf = new AccuracyEvaluation();
//                    AccuracyEvaluation twAccuracyEvaluationf = new AccuracyEvaluation();
//                    AccuracyEvaluation thAccuracyEvaluationf = new AccuracyEvaluation();
//                    AccuracyEvaluation forAccuracyEvaluationf = new AccuracyEvaluation();
//                    //构造返回对象
//                    CalResult calResult = new CalResult();
//                    //设置站码
//                    accuracyEvaluationResult.setStationCode(stcd);
//                    accuracyPeakResult.setStationCode(stcd);
//                    accuracyEvaluationResult.setStationName(bdms_st_sensor_bs.stream().filter(bdms_st_sensor_b1 -> bdms_st_sensor_b1.getStcd().equals(stcd)).findAny().get().getStnm());
//                    accuracyPeakResult.setStationName(bdms_st_sensor_bs.stream().filter(bdms_st_sensor_b1 -> bdms_st_sensor_b1.getStcd().equals(stcd)).findAny().get().getStnm());
//
//                    List<BDMS_FBC_RESULT_P> bdms_fbc_resultsList = bdms_fbc_results.stream().filter(BDMS_FBC_RESULT -> BDMS_FBC_RESULT.getPtkey().equals(stcd)).collect(Collectors.toList());
//                    //获取值
//                    for (BDMS_FBC_RESULT_P bdms_fbc_result : bdms_fbc_resultsList) {
//                        data_all(bdms_fbc_result.getDtvalues());
//                    }
//                    //获取values平均值
//                    Double avg;
//                    if (values != null) {
//                        for (int i = 0; i < values.size(); i++) {
//                            try {
//                                Date date = format.parse(StartTime);
//                                calendar.setTime(date);
//                                calendar.add(Calendar.HOUR, +i);
//                                dataList.add(new Data(format.format(calendar.getTime()), values.get(i)));
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    }
//                    dataList.sort(Comparator.comparing(Data::getTM));
//                    //站码  分组
//                    String datacode = bdms_st_sensor_bs.stream().filter(s -> s.getStcd().equals(stcd)).findAny().orElse(null).getDatacode();
//                    List<ST_TIDE_R> st_tide_rs = st_tide_rList.stream().filter(ST_TIDE_R -> ST_TIDE_R.getStcd().equals(datacode) && ST_TIDE_R.getMin().equals(min)).collect(Collectors.toList());
//                    List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFs = bdmsStAstrotdFList.stream().filter(BDMS_ST_ASTROTD_F -> BDMS_ST_ASTROTD_F.getStcd().equals(stcd)).collect(Collectors.toList());
//                    for (BDMS_ST_ASTROTD_F bdmsStAstrotdF : bdmsStAstrotdFs) {
//                        FtdzTime = bdmsStAstrotdF.getYmdh();
//                        for (Data data : dataList) {
//                            DataTime = data.getTM();
//                            if (bdmsStAstrotdF.getFtdz() != null) {
//                                //设置高低潮
//                                if (bdmsStAstrotdF.getHltdmk() != null && bdmsStAstrotdF.getHltdmk() > 0) {
//                                    //
//                                    PointResult pointHLResult = new PointResult();
//                                    pointHLResult.setTm(bdmsStAstrotdF.getYmdh());
//                                    //System.out.println(pointHLResult.getTm()+"hlp");
//                                    pointHLResult.setTwc(bdmsStAstrotdF.getFtdz());
//                                    pointHLResults.add(pointHLResult);
//                                } else {
//                                    //设置天文潮预报对象
//                                    PointResult pointResult = new PointResult();
//                                    pointResult.setTm(bdmsStAstrotdF.getYmdh());
//                                    pointResult.setTwc(bdmsStAstrotdF.getFtdz());
//                                    String TM = FtdzTime;
//                                    if (st_tide_rs.size() > 0) {
//                                        ST_TIDE_R st_tide_r = st_tide_rs.stream().filter(ST_TIDE_R -> ST_TIDE_R.getTm().substring(0, 19).equals(TM.substring(0, 19))).findAny().orElse(null);
//                                        //通过时间获取数据
//                                        if (st_tide_r != null) {
//                                            pointResult.setTdz(st_tide_r.getTdz());
//                                        }
//                                    }
//                                    Data datas = dataList.stream().filter(Data -> Data.getTM().substring(0, 19).equals(TM.substring(0, 19))).findAny().orElse(null);
//                                    if (datas != null) {
//                                        if (datas.getTM().equals(FtdzTime)) {
//                                            pointResult.setTm(datas.getTM());
//                                            double zs = datas.getValue() * 100;
//                                            if (Math.abs(zs) < 10) {
//                                                ten++;
//                                            } else if (Math.abs(zs) < 20) {
//                                                twenty++;
//                                            } else if (Math.abs(zs) < 30) {
//                                                thirty++;
//                                            } else if (Math.abs(zs) >= 30) {
//                                                forty++;
//                                            }
//                                            pointResult.setZs(datas.getValue());
//                                            System.out.println("Zs"+datas.getValue());
//                                            double a = pointResult.getZs();
//                                            double b = bdmsStAstrotdF.getFtdz();
//                                            float a1 = (float) a;
//                                            float b1 = (float) b;
//                                            pointResult.setFtdz(Double.parseDouble(String.format("%.2f", a1 + b1)));
//                                        }
//                                    }
//                                    //特征值集合
//                                    pointResults.add(pointResult);
//                                    break;
//                                }
//                                break;
//                            }
//                        }
//                        // break;
//                    }
//                    //gouzao    PointHLResults 作业预报开始时间 结束之间 范围的数据  List  gouzao
//                    //判断
//                    try {
//                        calendar.setTime(format.parse(StartTime));
//                        calendar.add(Calendar.HOUR, -1);
//                        Date start = calendar.getTime();
//                        calendar.setTime(format.parse(EndTime));
//                        calendar.add(Calendar.HOUR, -1);
//                        Date end = calendar.getTime();
//                        List<PointResult> pointResults1 = pointResults.stream().filter(
//                                PointResult -> {
//                                    try {
//                                        return format.parse(PointResult.getTm()).after(start)
//                                                && format.parse(PointResult.getTm()).before(end);
//                                    } catch (ParseException e) {
//                                        e.printStackTrace();
//                                    }
//                                    return false;
//                                }).collect(Collectors.toList());
//                        List<PointResult> pointHLResults1 = pointHLResults.stream().filter(
//                                PointResult -> {
//                                    try {
//                                        return start.before(format.parse(PointResult.getTm())) &&
//                                                start.before(format.parse(PointResult.getTm()));
//                                    } catch (ParseException e) {
//                                        e.printStackTrace();
//                                    }
//                                    return false;
//                                }).collect(Collectors.toList());
//                        //   List<PointResult> pointHLResults2 = new ArrayList<>();
//                        for (PointResult result : pointHLResults1) {
//                            PointResult pointHLResult = new PointResult();
//                            String pointHLResultsYear = result.getTm().substring(0, 16);
//                            boolean res = Integer.parseInt(pointHLResultsYear.substring(14, 16)) >= 30;
//                            String time = pointHLResultsYear.substring(0, 13) + ":00:00.0";
//                            Date Time = format.parse(time);
//                            calendar.setTime(Time);
//                            if (res) {
//                                calendar.add(Calendar.HOUR, +1);
//                            }
//                            String day = format.format(calendar.getTime());
//                            //根据日期去获取对应的逐时
//                            PointResult pointResult = pointResults1.stream().filter(PointResult -> PointResult.getTm().equals(day)).findAny().orElse(null);
//                            if (pointResult != null) {
//                                pointHLResult.setTm(result.getTm());
//                                String tm = pointHLResult.getTm();
//                                pointHLResult.setZs(pointResult.getZs());
//                                pointHLResult.setTwc(result.getTwc());
//                                pointHLResult.setFtdz(pointHLResult.getZs() + pointHLResult.getTwc());
//                                for (PointResult pointHLs : pointHLResults) {
//                                    if (pointHLs.getTm().equals(tm)) {
//                                        pointHLs.setTm(tm);
//                                        pointHLs.setTwc(pointHLResult.getTwc());
//
//                                        double zs = pointHLResult.getZs() * 100;
//                                        if (Math.abs(zs) < 10) {
//                                            ten_t++;
//                                        } else if (Math.abs(zs) < 20) {
//                                            twenty_t++;
//                                        } else if (Math.abs(zs) < 30) {
//                                            thirty_t++;
//                                        } else if (Math.abs(zs) >= 30) {
//                                            forty_t++;
//                                        }
//
//                                        pointHLs.setZs(pointHLResult.getZs());
//                                        pointHLs.setFtdz(pointHLs.getZs() + pointHLs.getTwc());
//                                    }
//                                }
//                            }
//                        }
//                        calResult.setPointResults(pointResults);
//                        calResult.setPointHLResults(pointHLResults);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    List<PointResult> pointResultsFtdz = calResult.getPointResults().stream().filter(PointResult -> PointResult.getFtdz() != null).collect(Collectors.toList());
//                    PointResult poFtzd = pointResultsFtdz.stream().max(Comparator.comparing(PointResult::getFtdz)).orElse(null);
//                    if (poFtzd != null) {
//                        calResult.setMaxFtdzTm(poFtzd.getTm());
//                        calResult.setMaxFtdz(poFtzd.getFtdz());
//                    }
//                    int res = calResult.getPointResults().size();
//
//                    int ten_f = 0;
//                    int twenty_f = 0;
//                    int thirty_f = 0;
//                    int forty_f = 0;
//                    for (PointResult pointResult : calResult.getPointResults()) {
//                        if (pointResult.getTdz() != null) {
//                            double zs = calResult.getMaxFtdz() - pointResult.getTdz();
//                            System.out.println(calResult.getMaxFtdz()+"  "+pointResult.getTdz());
//                            if (Math.abs(zs) < 10) {
//                                ten_f++;
//                            } else if (Math.abs(zs) < 20) {
//                                twenty_f++;
//                            } else if (Math.abs(zs) < 30) {
//                                thirty_f++;
//                            } else if (Math.abs(zs) >= 30) {
//                                forty_f++;
//                            }
//                        }
//
//                    }
//                    //峰值
//                    tenAccuracyEvaluationf.setStandardRange("<±10cm");
//                    double df = (double) ten_f / res;
//
//                    Statistics processStatisticsf = new Statistics();
//                    processStatisticsf.setQualifiedNumber(ten + "/" + res);
//                    processStatisticsf.setQualifiedRate(Math.round(df * 100) + "%");
//                    tenAccuracyEvaluationf.setProcessResult(processStatisticsf);
//                    accuracyPeaks.add(tenAccuracyEvaluationf);
//
//                    twAccuracyEvaluationf.setStandardRange("<±20cm");
//                    double d2f = (double) twenty_f / res;
//                   // System.out.println(d2f);
//                    Statistics twprocessStatisticsf = new Statistics();
//                    twprocessStatisticsf.setQualifiedNumber(twenty_f + "/" + res);
//                    twprocessStatisticsf.setQualifiedRate(Math.round(d2f * 100) + "%");
//                    twAccuracyEvaluation.setProcessResult(twprocessStatisticsf);
//                    accuracyPeaks.add(twAccuracyEvaluationf);
//
//                    thAccuracyEvaluationf.setStandardRange("<±30cm");
//                    double d3f = (double) (thirty_f) / res;
//                    Statistics thprocessStatisticsf = new Statistics();
//                    thprocessStatisticsf.setQualifiedNumber((thirty_f) + "/" + res);
//                    thprocessStatisticsf.setQualifiedRate((Math.round(d3f * 100)) + "%");
//                    thAccuracyEvaluationf.setProcessResult(thprocessStatisticsf);
//                    accuracyPeaks.add(thAccuracyEvaluationf);
//
//                    forAccuracyEvaluationf.setStandardRange("≥±30cm");
//                    double d4f = (double) (forty_f) / res;
//                    Statistics foprocessStatisticsf = new Statistics();
//                    foprocessStatisticsf.setQualifiedNumber((forty_f) + "/" + res);
//                    foprocessStatisticsf.setQualifiedRate(Math.round(d4f * 100) + "%");
//                    forAccuracyEvaluationf.setProcessResult(foprocessStatisticsf);
//                    accuracyPeaks.add(forAccuracyEvaluationf);
//
//                    accuracyPeakResult.setAccuracyPeaks(accuracyPeaks);
//                    accuracyPorkResults.add(accuracyPeakResult);
//
//
//                    //
//                    tenAccuracyEvaluation.setStandardRange("<±10cm");
//                    double d = (double) (ten) / res;
//                    Statistics processStatistics = new Statistics();
//                    processStatistics.setQualifiedNumber(ten + "/" + res);
//                    processStatistics.setQualifiedRate(Math.round(d * 100) + "%");
//                    tenAccuracyEvaluation.setProcessResult(processStatistics);
//                    accuracyEvaluations.add(tenAccuracyEvaluation);
//
//                    twAccuracyEvaluation.setStandardRange("<±20cm");
//                    double d2 = (double) (ten + twenty) / res;
//                    Statistics twprocessStatistics = new Statistics();
//                    twprocessStatistics.setQualifiedNumber((ten + twenty) + "/" + res);
//                    twprocessStatistics.setQualifiedRate(Math.round(d2 * 100) + "%");
//                    twAccuracyEvaluation.setProcessResult(twprocessStatistics);
//                    accuracyEvaluations.add(twAccuracyEvaluation);
//
//                    thAccuracyEvaluation.setStandardRange("<±30cm");
//                    double d3 = (double) (ten + twenty + thirty) / res;
//                    Statistics thprocessStatistics = new Statistics();
//                    thprocessStatistics.setQualifiedNumber((ten + twenty + thirty) + "/" + res);
//                    thprocessStatistics.setQualifiedRate((Math.round(d3 * 100)) + "%");
//                    thAccuracyEvaluation.setProcessResult(thprocessStatistics);
//                    accuracyEvaluations.add(thAccuracyEvaluation);
//
//                    forAccuracyEvaluation.setStandardRange("≥±30cm");
//                    double d4 = (double) (forty) / res;
//                    Statistics foprocessStatistics = new Statistics();
//                    foprocessStatistics.setQualifiedNumber((forty) + "/" + res);
//                    foprocessStatistics.setQualifiedRate(Math.round(d4 * 100) + "%");
//                    forAccuracyEvaluation.setProcessResult(foprocessStatistics);
//                    accuracyEvaluations.add(forAccuracyEvaluation);
//
//                    accuracyEvaluationResult.setAccuracyEvaluations(accuracyEvaluations);
//                    accuracyEvaluationResults.add(accuracyEvaluationResult);
//                }
//
//            }
            forecastDifference.setAccuracyEvaluationResults(accuracyEvaluationResults);
            forecastDifference.setAccuracyPeaksResults(accuracyPorkResults);
            list.add(forecastDifference);
        }
        return list;
    }


    //获取产品类型
    public List<ProductInfoResult> getProductType(Integer projectId) {
        List<ProductInfoResult> productInfoResults = new ArrayList<>();
        List<String> infoIds = new ArrayList<>();
        //根据项目id获取产品id
        List<BDMS_PRODUCT_PROJ_LINK> bdms_product_proj_links = bdms_product_proj_linkService.queryById(projectId);
        if (bdms_product_proj_links!=null&&bdms_product_proj_links.size()>0) {
            for (BDMS_PRODUCT_PROJ_LINK bdms_product_proj_link : bdms_product_proj_links) {
                infoIds.add(bdms_product_proj_link.getInfoid());
            }
            //根据产品id获取对应产品
            List<BDMS_PRODUCT_INFO> bdms_product_infos = bdms_product_infoService.queryByIds(infoIds);
            Map<String, List<BDMS_PRODUCT_INFO>> typeListGroup = bdms_product_infos.stream().collect(Collectors.groupingBy(BDMS_PRODUCT_INFO::getInfotp, Collectors.toList()));
            for (Map.Entry<String, List<BDMS_PRODUCT_INFO>> typeList : typeListGroup.entrySet()) {
                ProductInfoResult productInfoResult = new ProductInfoResult();
                productInfoResult.setInfoType(typeList.getKey());
                List<ProductInfo> productInfos = new ArrayList<>();
                for (BDMS_PRODUCT_INFO bdmsProductInfo : typeList.getValue()) {
                    ProductInfo productInfo = new ProductInfo();
                    productInfo.setInfoId(bdmsProductInfo.getInfoid());
                    productInfo.setInfoName(bdmsProductInfo.getInfonm());
                    productInfo.setDattp(bdmsProductInfo.getDattp());
                    productInfo.setGendat(bdmsProductInfo.getGendat());
                    productInfo.setFileType(bdmsProductInfo.getFiletype());
                    productInfo.setFilenmfmt(bdmsProductInfo.getFilenmfmt());
                    productInfos.add(productInfo);
                }
                productInfoResult.setProductInfos(productInfos);
                productInfoResults.add(productInfoResult);
            }
        }
        return productInfoResults;
    }

    //获取预报方案集
    public List<CalSchemeInfo> getProductPrograms(Integer projectId, String infoId, Integer typhoonId) {
        //创建返回对象
        List<CalSchemeInfo> calSchemeInfos = new ArrayList<>();
        //创建方案id集合
        List<String> productIds = new ArrayList<>();
        //根据台风id,infoId,projectId获取方案集合
        List<BDMS_PRODUCT_RESULT> bdms_product_results = bdms_product_resultService.queryByProjectId(projectId, infoId, typhoonId);
        //循环成果集合
        for (BDMS_PRODUCT_RESULT bdms_product_result : bdms_product_results) {
            productIds.add(bdms_product_result.getProdid());
        }
        //根据方案id集合获取对应方案
        List<BDMS_CALCULATESCHEME_M1> bdms_calculatescheme_ms = bdms_calculatescheme_mService.selectShcemeByCalIds(productIds);
        for (BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m : bdms_calculatescheme_ms) {
            CalSchemeInfo calSchemeInfo = new CalSchemeInfo();
            if (bdms_calculatescheme_m != null) {

                if (bdms_calculatescheme_m.getParams() != null) {
                    String[] a = new String[0];
                    a = bdms_calculatescheme_m.getParams().split(",");
                    calSchemeInfo.setTyphoonId(a[0]);

                    calSchemeInfo.setTyphoonDepart(a[1]);
                    calSchemeInfo.setModelPar(a[2]);
                }

                calSchemeInfo.setCalSchemeId(bdms_calculatescheme_m.getCschemeid());
                calSchemeInfo.setUserId(bdms_calculatescheme_m.getUserid());

                //根据modelid获取model名称
                BDMS_FBC_OCEANMODEL_B bdms_fbc_oceanmodel_b = bdms_fbc_oceanmodel_bService.getModelInfoByModelId(projectId, bdms_calculatescheme_m.getMdid());
                if (bdms_fbc_oceanmodel_b != null) {
                    calSchemeInfo.setModelId(bdms_fbc_oceanmodel_b.getModelid());
                    calSchemeInfo.setModelName(bdms_fbc_oceanmodel_b.getModelnm());
                }

                calSchemeInfo.setForecastOperateTime(bdms_calculatescheme_m.getDtmcalculate().substring(0, 19));
                calSchemeInfo.setForecastEndTime(bdms_calculatescheme_m.getDtmend().substring(0, 19));
                calSchemeInfo.setUserName("预报员");
                calSchemeInfo.setForecastTime(bdms_calculatescheme_m.getDtmforecast().substring(0, 19));
                calSchemeInfo.setState(String.valueOf(bdms_calculatescheme_m.getState()));
                calSchemeInfo.setRemark("state 0 新建方案、1 计算中、2 计算失败、3 计算成功");
                calSchemeInfo.setHasGen(bdms_calculatescheme_m.getIsgen());
                calSchemeInfo.setHasArea(bdms_calculatescheme_m.getIsarea());
            }
            calSchemeInfos.add(calSchemeInfo);
        }

        return calSchemeInfos;
    }


    public String getPath() {
        return  System.getProperty("user.dir").replace("\\", "/");
    }

    //获取预报成果
    public List<ForecastResult> getForecastResult(Integer projectId, String infoId, String productId) throws Exception {
        List<ForecastResult> forecastResults = new ArrayList<>();
        //根据项目id和产品id获取对应方案信息
        List<BDMS_PRODUCT_RESULT> bdms_product_results = bdms_product_resultService.queryByProductId(projectId, infoId, productId);
        String read = null;
        //获取当前项目根目录

        //循环数据获取对应文件路径
        for (BDMS_PRODUCT_RESULT bdms_product_result : bdms_product_results) {
            ForecastResult forecastResultR = new ForecastResult();
            if (bdms_product_result.getRemark()!=null){
//                SpecialReport specialReport = JSON.parseObject(bdms_product_result.getRemark(), SpecialReport.class);
                JSONObject jsonObject =JSONObject.parseObject(bdms_product_result.getRemark());
                System.out.println("json:"+jsonObject);
                forecastResultR.setFileContent(bdms_product_result.getRemark());
                forecastResults.add(forecastResultR);
            }
//            String gendat = bdms_product_result.getGendat();
//            String[] fileNames = bdms_product_result.getFilenm().split(",");
//            for (String fileName : fileNames) {
//                ForecastResult forecastResult = new ForecastResult();
//                String path = relativelyPath + gendat + "/" + fileName;
//                System.out.println(path);
//                forecastResult.setFileName(fileName);
//                forecastResult.setFilePath(path);
//                read = GetDocPdfContentUtil.fileToBase64(path);
//                String[] array = read.split("\\r\\n");
//                StringBuilder sb = new StringBuilder();
//                for (String str : array) {
//                    sb.append(str);
//                }
//                read = sb.toString();
////                   GetDocPdfContentUtil.str2File(read,"E:\\Products\\1.pdf");
//                forecastResult.setFileContent(read);
//                forecastResults.add(forecastResult);
//            }
        }

        return forecastResults;
    }

    //生成专报
    private static void createTitle(XWPFDocument document, String text, boolean bold, int fontSize, String color,
                                    ParagraphAlignment paragraphAlignment, String fontFamily) {
        XWPFParagraph paragraph = document.createParagraph();
        paragraph.setAlignment(paragraphAlignment);
        XWPFRun run = paragraph.createRun();
        run.setText(text);
        run.setBold(bold);
        run.setFontFamily(fontFamily);
        run.setFontFamily("微软雅黑");
        run.setFontSize(fontSize);
        if (color != null) {
            run.setColor(color);
        }
        //paragraph.createRun().addBreak();
    }

    private static void setCellProperties(XWPFTableCell cell) {
        cell.setWidth("1440");
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
        XWPFParagraph paragraph = cell.getParagraphs().get(0);
        paragraph.setAlignment(ParagraphAlignment.CENTER);
    }

    private static void addBorder(XWPFDocument document, String color) {
        XWPFParagraph paragraph = document.createParagraph();
        CTBorder border = paragraph.getCTP().addNewPPr().addNewPBdr().addNewTop();
        border.setVal(STBorder.SINGLE);
        border.setSz(BigInteger.valueOf(2));
        border.setColor(color);
        paragraph.createRun().addBreak();
    }

    //根据预报方案id去获取对应台风信息数据
    public Map<String, Object> getTyphhonInfo(String calId, String infoId) throws Exception {
        BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m1 = bdms_calculatescheme_mService.selectShcemeByCalID(calId);
        Map<String, Object> infoMap = new HashMap<>();
        //获取modelid
        String modelId =bdms_calculatescheme_m1.getMdid();
        //根据modelId获取model名称
        BDMS_FBC_OCEANMODEL_B bdmsFbcOceanmodelB =  bdms_fbc_oceanmodel_bService.getModelInfoByModelId(bdms_calculatescheme_m1.getPid(),modelId);
        String modelAlias =bdmsFbcOceanmodelB.getModelnm();
        infoMap.put("model",modelAlias);

        //获取项目id
        int projectId = bdms_calculatescheme_m1.getPid();
        infoMap.put("projectId", projectId);
        //获取预报时间
        String forecastTime = bdms_calculatescheme_m1.getDtmforecast();
        infoMap.put("forecastTime", forecastTime);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = dateFormat.parse(forecastTime);
        int month = date.getMonth() + 1; // add 1 to get the actual month (January is 0)
        String monthStr = month + "月";
        int day = date.getDate();
        String dayStr = day + "日";
        int hour = date.getHours();
        String hourStr = hour + "时";
        String time = monthStr + dayStr + hourStr;
        infoMap.put("time", time);
        //获取台风编号
        String typhoonId = bdms_calculatescheme_m1.getParams().split(",")[0];
        //根据预报时间获取对应和台风id获取对应的台风实测路径
        BDMS_FBC_TFPATH_R bdmsFbcTfpathR = bdms_fbc_tfpath_rService.queryById(typhoonId, forecastTime);
        //获取抄送单位和报送单位
        BDMS_PRODUCT_PROJ_LINK bdms_product_proj_link = bdms_product_proj_linkService.queryAllByInfoid(projectId, infoId);
        String issDept = bdms_product_proj_link.getIssdept();
        infoMap.put("issDept", issDept);
        String subDept = bdms_product_proj_link.getSubdept();
        infoMap.put("subDept", subDept);
        //根据台风id获取对应台风名称
        BDMS_FBC_TFINFO_B bdms_fbc_tfinfo_b = bdms_fbc_tfinfo_bService.queryById(typhoonId);
        //台风名称
        String typhoonName = bdms_fbc_tfinfo_b.getTfnameC();
        infoMap.put("typhoonName", typhoonName);
        //今年第19号台风“南川”（热带风暴），08时台风中心位北纬21.8度、东经151.4度，中心附近最大风力8级（20米/秒），中心最低气压为995百帕。
        String overview = "    今年第" + typhoonId.substring(4, 6) + "号台风“" + typhoonName + "”" +
                hourStr + "台风中心北纬" + bdmsFbcTfpathR.getLgtd() + "度、东经" + bdmsFbcTfpathR.getLttd() + "度，中心最大风力" +
                bdmsFbcTfpathR.getPower() + "级，中心最低气压为" + bdmsFbcTfpathR.getPressure() + "百帕";

        infoMap.put("overview", overview);
        //潮位影响分析 analyse  受“南川”外围影响，绿华山m;洋山港站的最高潮位为m;堡镇站的最高潮位为m;高桥站的最高潮位为m;崇西闸站的最高潮位为m;吴淞站的最高潮位为m;芦潮港站的最高潮位为m;金山嘴站的最高潮位为m;
        String analyse = "    受“" + typhoonName + "”外围影响";

        //获取预报站的预报结果
        //根据项目id获取站点信息
        List<BDMS_ST_STBPRP_B> bdmsStStbprpBList = bdms_st_stbprp_bService.selectStationByProject(projectId);
        List<String> dataCodes = new ArrayList<>();
        for (BDMS_ST_STBPRP_B bdmsStStbprpB : bdmsStStbprpBList) {
            dataCodes.add(bdmsStStbprpB.getStcd());
        }
        //dataCodes.add("70301400");
        StringBuilder result = new StringBuilder();
        List<Map<String, Object>> data = new ArrayList<>();
        List<String> str = new ArrayList<>();
        str.add(calId);
        List<CalResults> calResultsList = getBdms_fbc_result2(projectId, str, dataCodes, 0, 0, 0, null);
        for (CalResult calResult : calResultsList.get(0).getCalResults()) {
            BDMS_ST_STBPRP_B bdms_st_stbprp_b = bdmsStStbprpBList.stream().filter(BDMS_ST_STBPRP_B -> BDMS_ST_STBPRP_B.getStcd().equals(calResult.getStationCode())).findAny().orElse(null);
            if (bdms_st_stbprp_b != null) {
                Map<String, Object> station = new HashMap<>();
                station.put("站名", bdms_st_stbprp_b.getStnm());
                station.put("天文潮时", calResult.getMaxTwcTm());
                station.put("天文高潮(m)", String.valueOf(calResult.getMaxTwc()));
                station.put("预报潮时", calResult.getMaxFtdzTm());
                station.put("预报潮位(m)", String.valueOf(calResult.getMaxFtdz()));
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime targetDateTime = LocalDateTime.parse(calResult.getMaxFtdzTm(), formatter);
                LocalDateTime roundedDateTime = targetDateTime.withMinute(targetDateTime.getMinute() < 30 ? 0 : 30).withSecond(0);
                PointResult Result = null;
                for (PointResult pointResult : calResult.getPointResults()) {
                    LocalDateTime pointDateTime = LocalDateTime.parse(pointResult.getTm(), formatter);
                    if (pointDateTime.equals(roundedDateTime)) {
                        Result = pointResult;
                        break;
                    }
                }
                if (Result != null) {
                    station.put("增水(m)", String.valueOf(Result.getZs()));
                }
                // }
                result.append(bdms_st_stbprp_b.getStnm()).append("站的最高潮位为").append(calResult.getMaxFtdz()).append("m;");
                System.out.println("station"+station);
                data.add(station);
            }
        }
        infoMap.put("data", data);
        infoMap.put("analyse", (analyse + result));
        return infoMap;
    }

    public String GetSpecialReport(String calSchemeId, List<String> infoIds) throws Exception {
        //根据方案编号获取对应方案信息
        BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m1 = bdms_calculatescheme_mService.selectShcemeByCalID(calSchemeId);
        //方案信息不为空返回数据
        if (bdms_calculatescheme_m1!=null){
            //循环infoids
            for (String infoId : infoIds) {
                System.out.println(infoId);
                switch (infoId) {
                    case "FbcResultWord72":
                        GenSpecialReportNBnew(calSchemeId, infoId);
                        break;
                    case "FbcResultWord72All":
                        GenSpecialReportNBnewAll(calSchemeId, infoId);
                        break;
                    case "FbcReportWord1":
                        SpecialReport specialReport = new SpecialReport();
                        List<String> strings = new ArrayList<>();
                        List<ReportResult> reportResults = new ArrayList<>();
                        List<String> stringList = new ArrayList<>();
                        List<String> calSchemeIds = new ArrayList<>();
                        calSchemeIds.add(calSchemeId);
                        //设置标题
                        strings.add("风暴潮分析专报");
                        //设置年份
                        strings.add(bdms_calculatescheme_m1.getDtmforecast().substring(0, 4) + "年");
                        //获取项目编号
                        Integer projectId = bdms_calculatescheme_m1.getPid();
                        //获取model编号
                        //根据modelId获取model名称
                        //String modelAlias =bdmsFbcOceanmodelB.getModelnm();

                        //获取预报时间
                        String forecastTime = bdms_calculatescheme_m1.getDtmforecast();
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date date = dateFormat.parse(forecastTime);
                        int month = date.getMonth() + 1; // add 1 to get the actual month (January is 0)
                        String monthStr = month + "月";
                        int day = date.getDate();
                        String dayStr = day + "日";
                        int hour = date.getHours();
                        String hourStr = hour + "时";
                        String time = monthStr + dayStr + hourStr;
                        //获取台风编号
                        String typhoonId = bdms_calculatescheme_m1.getParams().split(",")[0];
                        //根据预报时间获取对应和台风id获取对应的台风实测路径
                        BDMS_FBC_TFPATH_R bdmsFbcTfpathR = bdms_fbc_tfpath_rService.queryById(typhoonId, forecastTime);
                        //获取抄送单位和报送单位
                        BDMS_PRODUCT_PROJ_LINK bdms_product_proj_link = bdms_product_proj_linkService.queryAllByInfoid(projectId, infoId);
                        String issDept = bdms_product_proj_link.getIssdept();
                        //设置发送单位 以及时间
                        strings.add(issDept + "     " + time);
                        String subDept = bdms_product_proj_link.getSubdept();
                        //根据台风id获取对应台风名称
                        BDMS_FBC_TFINFO_B bdms_fbc_tfinfo_b = bdms_fbc_tfinfo_bService.queryById(typhoonId);
                        //台风名称
                        String typhoonName = bdms_fbc_tfinfo_b.getTfnameC();
                        strings.add("台风”" + typhoonName + "“风暴潮预报分析");
                        strings.add("一、台风概况");
                        //今年第19号台风“南川”（热带风暴），08时台风中心位北纬21.8度、东经151.4度，中心附近最大风力8级（20米/秒），中心最低气压为995百帕。
                        String overview = "    今年第" + typhoonId.substring(4, 6) + "号台风“" + typhoonName + "”" +
                                hourStr + "台风中心北纬" + String.format("%.2f", Double.valueOf(bdmsFbcTfpathR.getLgtd())) + "度、东经" + String.format("%.2f", Double.valueOf(bdmsFbcTfpathR.getLttd())) + "度，中心最大风力" +
                                bdmsFbcTfpathR.getPower() + "级，中心最低气压为" + bdmsFbcTfpathR.getPressure() + "百帕";
                        strings.add(overview);
                        strings.add("二、潮位影响分析");
                        //潮位影响分析 analyse  受“南川”外围影响，绿华山m;洋山港站的最高潮位为m;堡镇站的最高潮位为m;高桥站的最高潮位为m;崇西闸站的最高潮位为m;吴淞站的最高潮位为m;芦潮港站的最高潮位为m;金山嘴站的最高潮位为m;
                        String analyse = "    受“" + typhoonName + "”外围影响";
                        //获取项目id下所有的站点信息
                        List<BDMS_ST_STBPRP_B> bdmsStStbprpBList = bdms_st_stbprp_bService.selectStationByProject(projectId);
                        StringBuilder result = new StringBuilder();
                        for (BDMS_ST_STBPRP_B bdmsStStbprpB : bdmsStStbprpBList) {
                            ReportResult reportResult = new ReportResult();
                            com.jhhc.utils.CalResult calResult = getDataUtil.getDataByCalSchemeIds(projectId, calSchemeIds, bdmsStStbprpB.getStcd(), 0, 0, 0, 0);
                            //预报潮位
                            if (calResult.getCalSchemeInfos().get(0).getResults().size() > 2) {
                                Double ftdz = calResult.getCalSchemeInfos().get(0).getResults().get(1).getMaxData().getValue();
                                //预报潮位时间
                                String maxtime = calResult.getCalSchemeInfos().get(0).getResults().get(1).getMaxData().getTM();
                                Data dataTWC = calResult.getBaseDatas().stream().filter(chartData -> chartData.getSensorType().equals("twc")).findFirst().get().getDatas().stream().filter(data -> data.getTM().substring(0, 19).equals(maxtime.substring(0, 19))).findAny().orElse(null);
                                Double twc = null;
                                if (dataTWC != null) {
                                    twc = dataTWC.getValue();
                                }
                                Data dataZs = calResult.getCalSchemeInfos().get(0).getResults().get(0).getDatas().stream().filter(data -> data.getTM().substring(0, 19).equals(maxtime.substring(0, 19))).findAny().orElse(null);
                                //System.out.println(dataZs);
                                //System.out.println(dataZs);
                                //System.out.println(dataZs);
                                Double zs = null;
                                if (dataZs != null) {
                                    zs = dataZs.getValue();
                                }
                                reportResult.setStationName(bdmsStStbprpB.getStnm());
                                reportResult.setTwcTime(dataTWC.getTM());
                                reportResult.setTwcMax(String.valueOf(twc));
                                reportResult.setForecastTime(maxtime);
                                reportResult.setFtdz(String.valueOf(ftdz));
                                reportResult.setZs(String.valueOf(zs));
                                reportResults.add(reportResult);
                                result.append(bdmsStStbprpB.getStnm()).append("站的最高潮位为").append(calResult.getCalSchemeInfos().get(0).getResults().get(1).getMaxData().getValue()).append("m;");
                            }
                        }
                        analyse = analyse + result;
                        strings.add(analyse);
                        stringList.add(issDept + "密切关注台风动向，加强气象、水文、海洋等信息的收集，进一步做好预测预报和分析工作。");
                        stringList.add("防御建议：各级防汛机构、沿江沿河各单位检查落实防范措施。");
                        stringList.add("报送：" + subDept);
                        stringList.add("签发：                 核稿：               分析：      ");
                        specialReport.setStrings(strings);
                        specialReport.setReportResults(reportResults);
                        specialReport.setStringList(stringList);
                        //原始代码块
                        BDMS_PRODUCT_RESULT bdmsProductResult = new BDMS_PRODUCT_RESULT();
                        bdmsProductResult.setProdid(calSchemeId);
                        bdmsProductResult.setInfoid(infoId);
                        //int projectId = (Integer) infoMap.get("projectId");
                        bdmsProductResult.setPid(projectId);
                        bdmsProductResult.setGendat(getInformTxtUtil.getUUID());
                        String jsonString = JSON.toJSONString(specialReport);
                        bdmsProductResult.setRemark(jsonString);
                        bdms_product_resultService.insert(bdmsProductResult);
                        //当专报生成后去标记
                        //根据calId获取预报时间点 获取预报时间点下的所有计算方案 修改当前计算方案信息isgen=1
                        //  BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m1 = bdms_calculatescheme_mService.selectShcemeByCalID(calSchemeId);
                        String ybsj = bdms_calculatescheme_m1.getDtmforecast();
                        String tfid = bdms_calculatescheme_m1.getParams().split(",")[0];
                        //根据预报时间获取所有计算方案
                        List<BDMS_CALCULATESCHEME_M1> bdms_calculatescheme_m1s = bdms_calculatescheme_mService.selectShcemeByPidDate(projectId, tfid, ybsj, ybsj, null, "预报", null, null, null, null);
                        for (BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m : bdms_calculatescheme_m1s) {
                            if (bdms_calculatescheme_m.getCschemeid().equals(calSchemeId)) {
                                bdms_calculatescheme_mService.updateGen(calSchemeId, 1);
                            } else {
                                bdms_calculatescheme_mService.updateGen(bdms_calculatescheme_m.getCschemeid(), 0);
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
            return "生成成功";
        }else {
            return null;
        }
    }


    //风暴潮汇总文档
    public String GetSummaryOfStormSurgeForecast(String calSchemeId, String infoId, List<com.jhhc.utils.CalResult> calResults) throws Exception {
        //根据预报方案获取预报时间点
        BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m1 = bdms_calculatescheme_mService.selcalSchemeId(calSchemeId);
        //获取预报时间点
        String forecastTime =bdms_calculatescheme_m1.getDtmforecast();
        String time =forecastTime.substring(0,4)+"年"+forecastTime.substring(5,7)+"月"
                +forecastTime.substring(8,10)+"日"+forecastTime.substring(11,13)+"时";
        String time2 =forecastTime.substring(5,7)+"月"
                +forecastTime.substring(8,10)+"日"+forecastTime.substring(11,13)+"时";
        //访问请求获取到图片
        // 发送第一个GET请求

        String firstUrl = "http://180.96.23.207:2109/Weathers/Picture/GetPictureList?productSource=%E4%B8%AD%E5%A4%AE%E6%B0%94%E8%B1%A1%E5%8F%B0&productType=%E5%8F%B0%E9%A3%8E%E8%B7%AF%E5%BE%84%E9%A2%84%E6%8A%A5&pictureType=%E5%8F%B0%E9%A3%8E%E8%B7%AF%E5%BE%84%E9%A2%84%E6%8A%A5%E5%9B%BE2&startTime=2023-07-28+02:00:00&endTime=2023-07-28+08:00:00";
        CloseableHttpClient httpClient = HttpClients.createDefault();  //http请求
        HttpGet httpPost = new HttpGet(firstUrl);
        httpPost.addHeader("Content-Type", "application/json");
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String responseContent = EntityUtils.toString(entity);
        JSONObject json = JSON.parseObject(responseContent);
        JSONObject json1 = json.getJSONObject("data");
        // 获取pictureList数组
        JSONArray pictureList = json1.getJSONArray("pictureList");
        // 获取第一个元素
        JSONObject picture = pictureList.getJSONObject(0);
        // 获取absolutepath和relativepath的值
        String absolutepath = picture.getString("absolutepath");
        String relativepath = picture.getString("relativepath");
        String encodedURL = URLEncoder.encode(relativepath);
        //创建请求获取到图片
        String url ="http://180.96.23.207:2109/Weathers/Picture/GetSingle?absolutepath="+absolutepath+"&relativepath="+encodedURL;
        //
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("Content-Type", "application/json");
        CloseableHttpResponse response1 = httpClient.execute(httpGet);
//        JSONObject jsonobject = JSONObject.parseobject(result);
//        String data = (String) jsonObject.get("data"):
        HttpEntity entity1 = response1.getEntity();
        String image = EntityUtils.toString(entity1);


        JSONObject jsonImage = JSON.parseObject(image);

        String images = jsonImage.getString("data");
        // System.out.println("123:"+images);
        //请求到image后转码
        ImageBase64 imageBase64  =new ImageBase64();

        UUID uuid = UUID.randomUUID();
        String uniqueId = uuid.toString();

        //getPath()+"/Products/"+uniqueId+"ima.jpg
        imageBase64.Base64ToconvertFile( imageBase64.getURLDecoderString(String.valueOf(images)),"E://1.jpg");
        try {
            XWPFDocument document = new XWPFDocument();
            createTitle(document, "202305号强台风“杜苏芮”风暴潮预报汇总表", true, 20, "000000", ParagraphAlignment.CENTER, "黑体");
            //Calendar calendar = Calendar.getInstance();
            createTitle(document, "作业预报时间："+time, false, 14, "FF0000", ParagraphAlignment.BOTH, "等线");

            // addBorder(document, "000000");
            createTitle(document, "预报路径："+time, false, 14, "FF0000", ParagraphAlignment.BOTH, "等线");
            createTitle(document, "预报模型："+time, false, 14, "FF0000", ParagraphAlignment.BOTH, "等线");
            createTitle(document, "预报单位："+time, false, 14, "FF0000", ParagraphAlignment.BOTH, "等线");


            // 将图片添加到XWPFDocument中
            XWPFParagraph paragraph = document.createParagraph();
            XWPFRun run = paragraph.createRun();
            int width;
            int height;
            width = Units.toEMU(400); // 替换成你想要的图片宽度
            height = Units.toEMU(300); // 替换成你想要的图片高度getPath()
            run.addPicture(Files.newInputStream(Paths.get("E://1.jpg")), XWPFDocument.PICTURE_TYPE_PNG, "图片描述",width,height);
            createTitle(document, "浙江", false, 15, null, ParagraphAlignment.CENTER, "仿宋");
            //createTitle(document," 预报模型："+ infoMap.get("model"),false,15,null,ParagraphAlignment.BOTH, "仿宋");
            // 创建表格
            XWPFTable table = document.createTable(4, 8);

            // 设置表格样式
            // 设置第一行的列头
            XWPFTableRow headerRow1 = table.getRow(0);
            headerRow1.getCell(0).setText("站名");
            headerRow1.getCell(1).getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            headerRow1.getCell(2).getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
            headerRow1.getCell(3).getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
            headerRow1.getCell(1).setText("日最高潮位(m)");
            headerRow1.getCell(4).setText("最大增水(m)");
            headerRow1.getCell(5).setText("时间");
            headerRow1.getCell(6).setText("警戒潮位(m)");
            headerRow1.getCell(7).setText("超警(m)");

            // 合并第一行的除了第2.3.4列的其他列
            for (int i = 0; i < 8; i++) {
                if (i != 1 && i != 2 && i != 3) {
                    headerRow1.getCell(i).getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
                    table.getRow(1).getCell(i).getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
                }
            }

            // 设置第二行的列头
            XWPFTableRow headerRow2 = table.getRow(1);
            headerRow2.getCell(1).setText("27日");
            headerRow2.getCell(2).setText("28日");
            headerRow2.getCell(3).setText("29日");

            // 设置数据
            XWPFTableRow dataRow = table.getRow(2);
            dataRow.getCell(0).setText("闸口");
            dataRow.getCell(1).setText("3.64");
            dataRow.getCell(2).setText("3.71");
            dataRow.getCell(3).setText("3.86");
            dataRow.getCell(4).setText("0.18");
            dataRow.getCell(5).setText("28日13时");
            dataRow.getCell(6).setText("6.88");
            // 设置警戒潮位和超警值

            for (com.jhhc.utils.CalResult calResult :calResults){
              //  JFreeChart jFreeChart = jfreeChartUtils.createChart(calResult);
                // 创建一个段落
                XWPFParagraph paragraph2 = document.createParagraph();

                // 创建JFreeChart图表
                JFreeChart jFreeChart = jfreeChartUtils.createChart(calResult);
                // 将JFreeChart图表转换为BufferedImage对象
                BufferedImage image2 = jFreeChart.createBufferedImage(1200, 800, null);

// 将BufferedImage对象转换为InputStream对象
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                ImageIO.write(image2, "png", outputStream);
                InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());

// 将InputStream对象添加到Word文档中
                XWPFPicture picture2 = paragraph2.createRun().addPicture(inputStream, XWPFDocument.PICTURE_TYPE_PNG,null,1200,800);

            }

//            XWPFRun run2 = paragraph.createRun();
//             width = Units.toEMU(400); // 替换成你想要的图片宽度
//             height = Units.toEMU(300); // 替换成你想要的图片高度getPath()
//            run2.addPicture(Files.newInputStream(Paths.get("E://2.jpg")), XWPFDocument.PICTURE_TYPE_PNG, "图片描述",width,height);

            //先获取预报了几天的数据
            //获取预报方案的开始时间和结束时间
            // 创建新的段落
            Date start = format.parse(  bdms_calculatescheme_m1.getDtmforecast());
            Date end = format.parse(bdms_calculatescheme_m1.getDtmend());
            long diffInMillies = end.getTime() - start.getTime();
            long days = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
            int day =Integer.parseInt(String.valueOf(days))+1;
            int cols =4+day*4;
            File folder = new File(getPath() + "/Products/" + uniqueId);
            if (!folder.exists()) {
                boolean created = folder.mkdirs();
                if (created) {
                    System.out.println("Folder created successfully");
                } else {
                    System.out.println("Failed to create folder");
                }
            } else {
                System.out.println("Folder already exists");
            }
            String fileName = "水文站潮位研判";
            String filePath = getPath() + "/Products/" + uniqueId + "/" + fileName;
            FileOutputStream out = new FileOutputStream(filePath + ".docx");
            document.write(out);
            out.close();
            document.close();
            //实例化Document类的对象
            Document doc = new Document();
            //加载Word
            doc.loadFromFile(filePath + ".docx");
            //保存为PDF格式
            doc.saveToFile(filePath + ".pdf", FileFormat.PDF);
            doc.close();
            //int res = bdms_product_resultService.insert(bdmsProductResult);
            System.out.println("文档生成成功！" + "文档保存路径为:" + filePath + ".pdf");
            return "文档生成成功！," + "文档保存路径为:" + filePath + "docx," + filePath + ".pdf";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    //宁波文档
//    public String GenSpecialReportNB(String calSchemeId, String infoId) throws Exception {
//        SpecialReportNB specialReport = new SpecialReportNB();
//        List<String> strings = new ArrayList<>();
//        List<ResultReport> resultReports = new ArrayList<>();
//        List<ResultReport> resultReports2 = new ArrayList<>();
//        List<String> list = new ArrayList<>();
//        //根据预报方案获取预报时间点
//        BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m1 = bdms_calculatescheme_mService.selcalSchemeId(calSchemeId);
//        if (bdms_calculatescheme_m1!=null) {
//            BDMS_PRODUCT_RESULT bdmsProductResult = new BDMS_PRODUCT_RESULT();
//            bdmsProductResult.setProdid(calSchemeId);
//            bdmsProductResult.setInfoid(infoId);
//
//            bdmsProductResult.setPid(bdms_calculatescheme_m1.getPid());
//            //获取预报时间点
//            String forecastTime = bdms_calculatescheme_m1.getDtmforecast();
//            String time = forecastTime.substring(0, 4) + "年" + forecastTime.substring(5, 7) + "月"
//                    + forecastTime.substring(8, 10) + "日" + forecastTime.substring(11, 13) + "时";
//            String time2 = forecastTime.substring(5, 7) + "月"
//                    + forecastTime.substring(8, 10) + "日" + forecastTime.substring(11, 13) + "时";
//            //访问请求获取到图片
//            // 发送第一个GET请求
//            String firstUrl = "http://180.96.23.207:2109/Weathers/Picture/GetPictureList?productSource=%E4%B8%AD%E5%A4%AE%E6%B0%94%E8%B1%A1%E5%8F%B0&productType=%E5%8F%B0%E9%A3%8E%E8%B7%AF%E5%BE%84%E9%A2%84%E6%8A%A5&pictureType=%E5%8F%B0%E9%A3%8E%E8%B7%AF%E5%BE%84%E9%A2%84%E6%8A%A5%E5%9B%BE2&startTime=2023-07-28+02:00:00&endTime=2023-07-28+08:00:00";
//            CloseableHttpClient httpClient = HttpClients.createDefault();  //http请求
//            HttpGet httpPost = new HttpGet(firstUrl);
//            httpPost.addHeader("Content-Type", "application/json");
//            CloseableHttpResponse response = httpClient.execute(httpPost);
//            HttpEntity entity = response.getEntity();
//            String responseContent = EntityUtils.toString(entity);
//            JSONObject json = JSON.parseObject(responseContent);
//            JSONObject json1 = json.getJSONObject("data");
//            // 获取pictureList数组
//            JSONArray pictureList = json1.getJSONArray("pictureList");
//            // 获取第一个元素
//            JSONObject picture = pictureList.getJSONObject(0);
//            // 获取absolutepath和relativepath的值
//            String absolutepath = picture.getString("absolutepath");
//            String relativepath = picture.getString("relativepath");
//            String encodedURL = URLEncoder.encode(relativepath);
//            //创建请求获取到图片
//            String url = "http://180.96.23.207:2109/Weathers/Picture/GetSingle?absolutepath=" + absolutepath + "&relativepath=" + encodedURL;
//            //
//            HttpGet httpGet = new HttpGet(url);
//            httpGet.addHeader("Content-Type", "application/json");
//            CloseableHttpResponse response1 = httpClient.execute(httpGet);
////        JSONObject jsonobject = JSONObject.parseobject(result);
////        String data = (String) jsonObject.get("data"):
//            HttpEntity entity1 = response1.getEntity();
//            String image = EntityUtils.toString(entity1);
//
//
//            JSONObject jsonImage = JSON.parseObject(image);
//
//            String images = jsonImage.getString("data");
//            // System.out.println("123:"+images);
//            //请求到image后转码
//            ImageBase64 imageBase64 = new ImageBase64();
//
//            UUID uuid = UUID.randomUUID();
//            String uniqueId = uuid.toString();
//
//            //getPath()+"/Products/"+uniqueId+"ima.jpg   /HHDX/RiverStrong/Server/Java/
//            specialReport.setImageUrl(getPath()+"/tf.jpg");
//
//            imageBase64.Base64ToconvertFile(imageBase64.getURLDecoderString(String.valueOf(images)), getPath()+"/tf.jpg");
//            strings.add("水文站潮位研判");
//            strings.add("宁波市水文站");
//            strings.add("一、潮位研判");
//            strings.add("研判结果：（根据" + time2 + "），中央台预报路径");
//            strings.add("1、甬江干流潮位(水位)预报");
//            strings.add("根据气象预报，过程面雨量    到     毫米局部     毫米以上，考虑径流影响，预测甬江干流最高潮位       米，时间出现在  月  日  时左右，超保证，奉化江北渡站最高潮位      米，出现时间为  日  时左右，超保证接近历史最高。");
//            strings.add("甬江干流潮位 (水位) 预报         单位：米");
//            try {
//                XWPFDocument document = new XWPFDocument();
//                createTitle(document, "水文站潮位研判", true, 20, "000000", ParagraphAlignment.CENTER, "仿宋");
//                //Calendar calendar = Calendar.getInstance();
//                createTitle(document, "宁波市水文站                        " + time, false, 14, "000000", ParagraphAlignment.BOTH, "仿宋");
//                addBorder(document, "000000");
//                createTitle(document, "一、潮位研判", true, 16, null, ParagraphAlignment.BOTH, "宋体");
//                // 将图片添加到XWPFDocument中
//                XWPFParagraph paragraph = document.createParagraph();
//                XWPFRun run = paragraph.createRun();
//                int width = Units.toEMU(400); // 替换成你想要的图片宽度
//                int height = Units.toEMU(300); // 替换成你想要的图片高度getPath()
//                run.addPicture(Files.newInputStream(Paths.get("tf.jpg")), XWPFDocument.PICTURE_TYPE_PNG, "图片描述", width, height);
//
//                createTitle(document, "研判结果：（根据" + time2 + "），中央台预报路径"
//                        , false, 15, null, ParagraphAlignment.BOTH, "仿宋");
//                createTitle(document, " \t  1、甬江干流潮位(水位)预报", false, 16, null, ParagraphAlignment.BOTH, "宋体");
//                createTitle(document, " \t  根据气象预报，过程面雨量    到     毫米局部     毫米以上，考虑径流影响，预测甬江干流最高潮位       米，时间出现在  月  日  时左右，超保证，奉化江北渡站最高潮位      米，出现时间为  日  时左右，超保证接近历史最高。", false, 15, null, ParagraphAlignment.BOTH, "宋体");
//                createTitle(document, " 甬江干流潮位 (水位) 预报         单位：米", false, 15, null, ParagraphAlignment.CENTER, "仿宋");
//                //createTitle(document," 预报模型："+ infoMap.get("model"),false,15,null,ParagraphAlignment.BOTH, "仿宋");
//
//                //先获取预报了几天的数据
//                //获取预报方案的开始时间和结束时间
//
//                // 创建新的段落
//                Date start = format.parse(bdms_calculatescheme_m1.getDtmforecast());
//                Date end = format.parse(bdms_calculatescheme_m1.getDtmend());
//                long diffInMillies = end.getTime() - start.getTime();
//                long days = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
//                //int day = Integer.parseInt(String.valueOf(days)) + 1;
//                int cols = 4 + 2 * 4;
//
//                XWPFTable table = document.createTable(1, cols);
//                table.setWidth("100%");
//
//                table.setTableAlignment(TableRowAlign.CENTER);
//                // 设置表格的列头
//                XWPFTableRow headerRow1 = table.getRow(0);
//                //根据cals余数等于1来判断列表
//                //int columnWidth =table.getWidth()/cols;
//                for (int i = 0; i < cols; i++) {
//                    // table.getRow(0).getCell(i).setWidth(String.valueOf(columnWidth));
//
//                    if (i == 0) {
//                        headerRow1.getCell(0).setText("潮位站");
//                    } else if (i % 4 == 1 && i < cols - 3) {
//                        headerRow1.getCell(i).setText("潮时");
//                    } else if (i % 4 == 2 && i < cols - 3) {
//                        headerRow1.getCell(i).setText("预报潮位");
//                    } else if (i % 4 == 3 && i < cols - 3) {
//                        headerRow1.getCell(i).setText("增水");
//                    } else if (i % 4 == 0 && i < cols - 3) {
//                        headerRow1.getCell(i).setText("天文潮");
//                    } else if (i == cols - 3) {
//                        headerRow1.getCell(i).setText("历史极值");
//                    } else if (i == cols - 2) {
//                        headerRow1.getCell(i).setText("警戒潮位");
//                    } else if (i == cols - 1) {
//                        headerRow1.getCell(i).setText("保证潮位");
//                    }
//
//                }
//                // 设置单元格属性
//                for (int row = 0; row < table.getNumberOfRows(); row++) {
//                    XWPFTableRow tableRow = table.getRow(row);
//                    for (XWPFTableCell cell : tableRow.getTableCells()) {
//                        setCellProperties(cell);
//                    }
//                }
//                //根据计算方案id去获取预报值
//                List<String> strs = new ArrayList<>();
//                List<String> strtionCodes1 = new ArrayList<>();
//                List<NBReport> nbReports = new ArrayList<>();
//                strtionCodes1.add("70301400");
//                strtionCodes1.add("70301200");
//                strtionCodes1.add("70300800");
//                strs.add(calSchemeId);
//                List<BDMS_ST_SENSORALARM_B> bdms_st_sensoralarm_bs = bdms_st_sensoralarm_bService.selectByStcd2(strtionCodes1);
//                BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m11 = bdms_calculatescheme_mService.selectShcemeByCalID(calSchemeId);
//                for (String stationCode : strtionCodes1) {
//                    ResultReport resultReport = new ResultReport();
//                    List<NBrep> nBreps = new ArrayList<>();
//                    com.jhhc.utils.CalResult calResult = getDataUtil.getDataByCalSchemeIds(bdms_calculatescheme_m11.getPid(), strs, stationCode, 0, 0, 0, 0);
//                    com.jhhc.utils.ChartData FTDZchartData = calResult.getCalSchemeInfos().get(0).getResults().stream().filter(chartData1 -> "ftdz".equals(chartData1.getSensorType())).findAny().orElse(null);
//                    System.out.println("FTDZchartData"+FTDZchartData);
//                    List<Data> maxTowFTDZ = getTopTwoData(FTDZchartData,forecastTime.substring(0,10));
//                    List<Data> maxDatas = new ArrayList<>();
//                    //  System.out.println("最大值f"+maxTowFTDZ);
//                    com.jhhc.utils.ChartData TWCchartData = calResult.getBaseDatas().stream().filter(chartData1 -> "twc".equals(chartData1.getSensorType())).findAny().orElse(null);
//                    //循环数据，然后去匹配天文潮
//                    if (maxTowFTDZ!=null){
//                        for (Data data : maxTowFTDZ) {
//                            NBrep nBrep = new NBrep();
//                            Data newData = new Data();
//                            Data data1 = TWCchartData.getDatas().stream().filter(da -> da.getTM().equals(data.getTM())).findAny().orElse(null);
//                            newData.setTM(data.getTM());
//                            nBrep.setTm(data.getTM());
//                            //预报潮位
//                            newData.setValue(data.getValue());
//                            nBrep.setFtdz(String.valueOf(data.getValue()));
//                            if (data1 != null) {
//                                newData.setTwc(data1.getValue());
//                                nBrep.setTwc(String.valueOf(data.getValue()));
//                            }
//                            newData.setZs(Double.valueOf(df.format(newData.getValue() - newData.getTwc())));
//                            nBrep.setZs(String.valueOf(df.format(newData.getValue() - newData.getTwc())));
//                            nBreps.add(nBrep);
//                            maxDatas.add(newData);
//                        }
//                    }
//                    resultReport.setStnm(calResult.getStationName());
//
//                    NBReport nbReport = new NBReport();
//                    BDMS_ST_SENSORALARM_B sensoralarm_b = bdms_st_sensoralarm_bs.stream().filter(bdms_st_sensoralarm_b -> bdms_st_sensoralarm_b.getStcd().equals(stationCode)).findAny().orElse(null);
//                    //System.out.println("sensoralarm_b"+sensoralarm_b);
//                    //根据站码查询站点
//                    if (sensoralarm_b != null) {
//                        nbReport.setStationName(sensoralarm_b.getStnm());
//                        nbReport.setDatas(maxDatas);
//                        if (sensoralarm_b.getHistorymax() != null) {
//                            nbReport.setMax(sensoralarm_b.getHistorymax().replace(",", "\n"));
//                            resultReport.setLsData(sensoralarm_b.getHistorymax().replace(",", "\n"));
//                        }
//                        nbReport.setArm(String.valueOf(sensoralarm_b.getAlarmvalue()));
//                        nbReport.setBc(sensoralarm_b.getEnsure());
//
//                        //xin
//
//                        resultReport.setBcData(sensoralarm_b.getEnsure());
//                        resultReport.setArmData(String.valueOf(sensoralarm_b.getAlarmvalue()));
//                        //System.out.println(nbReport);
//                        nbReports.add(nbReport);
//                    }
//                    resultReport.setResults(nBreps);
//                    resultReports.add(resultReport);
//                }
//
//                specialReport.setStringList(strings);
//                specialReport.setResults(resultReports);
//                for (NBReport nbReport : nbReports) {
//                    XWPFTableRow dataRow = table.createRow();
//                    int colss = dataRow.getTableCells().size();
//                    System.out.println("共计多少列" + colss);
//                    //System.out.println(nbReport);
//                    for (int col = 0; col < dataRow.getTableCells().size(); col++) {
//                        XWPFTableCell cell = dataRow.getCell(col);
//                        setCellProperties(cell);
//                    }
//                    dataRow.getCell(0).setText(nbReport.getStationName());
//                    int i = 0;
//                    for (Data data : nbReport.getDatas()) {
//                        System.out.println(data);
//                        if (data != null) {
//                            dataRow.getCell(1 + (4 * i)).setText(data.getTM());
//                            dataRow.getCell(2 + (4 * i)).setText(String.valueOf(data.getValue()));
//                            dataRow.getCell(3 + (4 * i)).setText(String.valueOf(data.getZs()));
//                            dataRow.getCell(4 + (4 * i)).setText(String.valueOf(data.getTwc()));
//                            i++;
//                        }
//
//                        //break;
//                    }
//                    dataRow.getCell(cols - 3).setText(nbReport.getMax());
//                    dataRow.getCell(cols - 2).setText(nbReport.getArm());
//                    dataRow.getCell(cols - 1).setText(nbReport.getBc());
//                }
//                list.add("2、沿海潮位预报");
//                list.add("未来    天，我市处于天文潮大潮期。按目前台风预报路径及其变\n" +
//                        "化趋势，南部三门湾海域预计高潮增水       ，象山东部海域\n" +
//                                "    米，象山港海域增水         米，北部杭州湾海域         米，我市沿海潮位代表站最高潮位达到或略超警戒。");
//                list.add("沿海潮位预报         单位：米");
//                createTitle(document,
//                        "   " + "2、沿海潮位预报"
//                        , false, 15, null, ParagraphAlignment.BOTH, "仿宋");
//                createTitle(document,
//                        "   " + "未来    天，我市处于天文潮大潮期。按目前台风预报路径及其变\n" +
//                                "化趋势，南部三门湾海域预计高潮增水       ，象山东部海域\n" +
//                                "    米，象山港海域增水         米，北部杭州湾海域         米，我市沿海潮位代表站最高潮位达到或略超警戒。"
//                        , false, 15, null, ParagraphAlignment.BOTH, "仿宋");
//                createTitle(document, " 沿海潮位预报         单位：米", false, 15, null, ParagraphAlignment.CENTER, "仿宋");
//
//                XWPFTable table2 = document.createTable(1, cols);
//                table2.setWidth("100%");
//                table2.setTableAlignment(TableRowAlign.CENTER);
//                // 设置表格的列头
//                XWPFTableRow headerRow2 = table2.getRow(0);
//                //根据cals余数等于1来判断列表
//                for (int i = 0; i < cols; i++) {
//                    if (i == 0) {
//                        headerRow2.getCell(0).setText("潮位站");
//                    } else if (i % 4 == 1 && i < cols - 3) {
//                        headerRow2.getCell(i).setText("潮时");
//                    } else if (i % 4 == 2 && i < cols - 3) {
//                        headerRow2.getCell(i).setText("预报潮位");
//                    } else if (i % 4 == 3 && i < cols - 3) {
//                        headerRow2.getCell(i).setText("增水");
//                    } else if (i % 4 == 0 && i < cols - 3) {
//                        headerRow2.getCell(i).setText("天文潮");
//                    } else if (i == cols - 3) {
//                        headerRow2.getCell(i).setText("历史极值");
//                    } else if (i == cols - 2) {
//                        headerRow2.getCell(i).setText("警戒潮位");
//                    } else if (i == cols - 1) {
//                        headerRow2.getCell(i).setText("保证潮位");
//                    }
//
//                }
//                // 设置单元格属性
//                for (int row = 0; row < table2.getNumberOfRows(); row++) {
//                    XWPFTableRow tableRow = table2.getRow(row);
//                    for (XWPFTableCell cell : tableRow.getTableCells()) {
//                        setCellProperties(cell);
//                    }
//                }
//                strtionCodes1.clear();
//                strtionCodes1 = new ArrayList<>();
//                nbReports.clear();
//                nbReports = new ArrayList<>();
//                //根据计算方案id去获取预报值
//                strtionCodes1.add("70007711");
//                strtionCodes1.add("70702791");
//                strtionCodes1.add("70703400");
//                strtionCodes1.add("70703800");
//                strtionCodes1.add("70704600");
//
//                bdms_st_sensoralarm_bs.clear();
//                bdms_st_sensoralarm_bs = bdms_st_sensoralarm_bService.selectByStcd2(strtionCodes1);
//                for (String stationCode : strtionCodes1) {
//
//                    ResultReport resultReport = new ResultReport();
//                    List<NBrep> nBreps = new ArrayList<>();
//                    com.jhhc.utils.CalResult calResult = getDataUtil.getDataByCalSchemeIds(bdms_calculatescheme_m11.getPid(), strs, stationCode, 0, 0, 0, 0);
//                    com.jhhc.utils.ChartData FTDZchartData = calResult.getCalSchemeInfos().get(0).getResults().stream().filter(chartData1 -> "ftdz".equals(chartData1.getSensorType())).findAny().orElse(null);
//                    List<Data> maxTowFTDZ = getTopTwoData(FTDZchartData,forecastTime.substring(0,10));
//                    List<Data> maxDatas = new ArrayList<>();
//                    //  System.out.println("最大值f"+maxTowFTDZ);
//                    com.jhhc.utils.ChartData TWCchartData = calResult.getBaseDatas().stream().filter(chartData1 -> "twc".equals(chartData1.getSensorType())).findAny().orElse(null);
//                    //循环数据，然后去匹配天文潮
//                    for (Data data : maxTowFTDZ) {
//                        NBrep nBrep = new NBrep();
//                        Data newData = new Data();
//                        Data data1 = TWCchartData.getDatas().stream().filter(da -> da.getTM().equals(data.getTM())).findAny().orElse(null);
//                        newData.setTM(data.getTM());
//                        nBrep.setTm(data.getTM());
//                        //预报潮位
//                        newData.setValue(data.getValue());
//                        nBrep.setFtdz(String.valueOf(data.getValue()));
//                        if (data1 != null) {
//                            newData.setTwc(data1.getValue());
//                            nBrep.setTwc(String.valueOf(data.getValue()));
//                        }
//                        newData.setZs(Double.valueOf(df.format(newData.getValue() - newData.getTwc())));
//                        nBrep.setZs(String.valueOf(df.format(newData.getValue() - newData.getTwc())));
//                        nBreps.add(nBrep);
//                        maxDatas.add(newData);
//                    }
//                    NBReport nbReport = new NBReport();
//                    BDMS_ST_SENSORALARM_B sensoralarm_b = bdms_st_sensoralarm_bs.stream().filter(bdms_st_sensoralarm_b -> bdms_st_sensoralarm_b.getStcd().equals(stationCode)).findAny().orElse(null);
//                    //System.out.println("sensoralarm_b"+sensoralarm_b);
//                    //根据站码查询站点
//                    if (sensoralarm_b != null) {
//                        resultReport.setStnm(sensoralarm_b.getStnm());
//                        nbReport.setStationName(sensoralarm_b.getStnm());
//                        nbReport.setDatas(maxDatas);
//                        if (sensoralarm_b.getHistorymax() != null) {
//                            nbReport.setMax(sensoralarm_b.getHistorymax().replace(",", "\n"));
//                            resultReport.setLsData(sensoralarm_b.getHistorymax().replace(",", "\n"));
//                        }
//                        nbReport.setArm(String.valueOf(sensoralarm_b.getAlarmvalue()));
//                        nbReport.setBc(sensoralarm_b.getEnsure());
//
//                        //xin
//
//                        resultReport.setBcData(sensoralarm_b.getEnsure());
//                        resultReport.setArmData(String.valueOf(sensoralarm_b.getAlarmvalue()));
//                        //System.out.println(nbReport);
//                        nbReports.add(nbReport);
//                    }
//                    resultReport.setResults(nBreps);
//                    resultReports2.add(resultReport);
//                }
//                specialReport.setStringList(list);
//                specialReport.setReports2(resultReports2);
//                for (NBReport nbReport : nbReports) {
//                    XWPFTableRow dataRow = table2.createRow();
//                    int colss = dataRow.getTableCells().size();
//
//                    //System.out.println(nbReport);
//                    for (int col = 0; col < dataRow.getTableCells().size(); col++) {
//                        XWPFTableCell cell = dataRow.getCell(col);
//                        setCellProperties(cell);
//                    }
//                    dataRow.getCell(0).setText(nbReport.getStationName());
//                    int i = 0;
//                    for (Data data : nbReport.getDatas()) {
//
//                        if (data != null) {
//                            dataRow.getCell(1 + (4 * i)).setText(data.getTM());
//                            dataRow.getCell(2 + (4 * i)).setText(String.valueOf(data.getValue()));
//                            dataRow.getCell(3 + (4 * i)).setText(String.valueOf(data.getZs()));
//                            dataRow.getCell(4 + (4 * i)).setText(String.valueOf(data.getTwc()));
//                            i++;
//                        }
//
//                        //break;
//                    }
//                    dataRow.getCell(cols - 2).setText(nbReport.getMax());
//                    dataRow.getCell(cols - 1).setText(nbReport.getArm());
//                    dataRow.getCell(cols - 1).setText(nbReport.getBc());
//                }
//
//                File folder = new File(getPath() + "/Products/" + uniqueId);
//                if (!folder.exists()) {
//                    boolean created = folder.mkdirs();
//                    if (created) {
//                        System.out.println("Folder created successfully");
//                    } else {
//                        System.out.println("Failed to create folder");
//                    }
//                } else {
//                    System.out.println("Folder already exists");
//                }
//                String fileName = "水文站潮位研判";
//                String filePath = getPath() + "/Products/" + uniqueId + "/" + fileName;
//                FileOutputStream out = new FileOutputStream(filePath + ".docx");
//                document.write(out);
//                out.close();
//                document.close();
//                //实例化Document类的对象
//                Document doc = new Document();
//                //加载Word
//                doc.loadFromFile(filePath + ".docx");
//                //保存为PDF格式
//                doc.saveToFile(filePath + ".pdf", FileFormat.PDF);
//                doc.close();
//                bdmsProductResult.setGendat(uniqueId);
//                bdmsProductResult.setCrttm(new Date());
//                //实例化Document类的对象
//                //加载Word
//                bdmsProductResult.setFilenm(fileName + ".docx," + fileName + ".pdf");
//                System.out.println(specialReport);
//                String jsonString = JSON.toJSONString(specialReport);
//                bdmsProductResult.setRemark(jsonString);
//                int res = bdms_product_resultService.insert(bdmsProductResult);
//                String ybsj =bdms_calculatescheme_m1.getDtmforecast();
//                String tfid = bdms_calculatescheme_m1.getParams().split(",")[0];
//                //根据预报时间获取所有计算方案
//                List<BDMS_CALCULATESCHEME_M1> bdms_calculatescheme_m1s= bdms_calculatescheme_mService.selectShcemeByPidDate(bdmsProductResult.getPid(),tfid,ybsj,ybsj,null,"预报",null,null,null,null);
//                for (BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m:bdms_calculatescheme_m1s){
//                    if (bdms_calculatescheme_m.getCschemeid().equals(calSchemeId)){
//                        bdms_calculatescheme_mService.updateGen(calSchemeId,1);
//                    }else {
//                        bdms_calculatescheme_mService.updateGen(bdms_calculatescheme_m.getCschemeid(),0);
//                    }
//                }
//                System.out.println("插入条数为"+res);
//                System.out.println("文档生成成功！" + "文档保存路径为:" + filePath + ".pdf");
//                return "文档生成成功！," + "文档保存路径为:" + filePath + "docx," + filePath + ".pdf";
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        return null;
//    }
    public String GenSpecialReportNBnew(String calSchemeId, String infoId) {
        SpecialReportNB specialReport = new SpecialReportNB();
        List<String> strings = new ArrayList<>();
        List<ResultReport> resultReports = new ArrayList<>();
        List<ResultReport> resultReports2 = new ArrayList<>();
        List<String> list = new ArrayList<>();
        //根据预报方案获取预报时间点
        BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m1 = bdms_calculatescheme_mService.selcalSchemeId(calSchemeId);
        if (bdms_calculatescheme_m1!=null) {
            BDMS_PRODUCT_RESULT bdmsProductResult = new BDMS_PRODUCT_RESULT();
            bdmsProductResult.setProdid(calSchemeId);
            bdmsProductResult.setInfoid(infoId);

            bdmsProductResult.setPid(bdms_calculatescheme_m1.getPid());
            //获取预报时间点
            String forecastTime = bdms_calculatescheme_m1.getDtmforecast();
            String time2 = forecastTime.substring(5, 7) + "月"
                    + forecastTime.substring(8, 10) + "日" + forecastTime.substring(11, 13) + "时";
            UUID uuid = UUID.randomUUID();
            String uniqueId = uuid.toString();
            strings.add("水文站潮位研判");
            strings.add("宁波市水文站");
            strings.add("一、潮位研判");
            strings.add("研判结果：（根据" + time2 + "），中央台预报路径");
            strings.add("1、甬江干流潮位(水位)预报");
            //strings.add("根据气象预报，过程面雨量    到     毫米局部     毫米以上，考虑径流影响，预测甬江干流最高潮位       米，时间出现在  月  日  时左右，超保证，奉化江北渡站最高潮位      米，出现时间为  日  时左右，超保证接近历史最高。");
            strings.add("甬江干流潮位 (水位) 预报         单位：米");
            try {
                //根据计算方案id去获取预报值
                List<String> strs = new ArrayList<>();
                List<String> strtionCodes1 = new ArrayList<>();
                strtionCodes1.add("70301400");
                strtionCodes1.add("70301200");
                strtionCodes1.add("70300800");
                strs.add(calSchemeId);
                List<BDMS_ST_SENSORALARM_B> bdms_st_sensoralarm_bs = bdms_st_sensoralarm_bService.selectByStcd2(strtionCodes1);
                //BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m11 = bdms_calculatescheme_mService.selectShcemeByCalID(calSchemeId);
                for (String stationCode : strtionCodes1) {
                    ResultReport resultReport = new ResultReport();
                    List<NBrep> nBreps = new ArrayList<>();
                    com.jhhc.utils.CalResult calResult = getDataUtil.getDataByCalSchemeIds(bdms_calculatescheme_m1.getPid(), strs, stationCode, 0, 0, 0, 0);
                    com.jhhc.utils.ChartData FTDZchartData = calResult.getCalSchemeInfos().get(0).getResults().stream().filter(chartData1 -> "tzzs".equals(chartData1.getSensorType())).findAny().orElse(null);
                    List<Data> maxTowFTDZ = getTopTwoData(FTDZchartData,forecastTime.substring(0,10));
                    List<Data> maxDatas = new ArrayList<>();
                    //  System.out.println("最大值f"+maxTowFTDZ);
                    com.jhhc.utils.ChartData TWCchartData = calResult.getBaseDatas().stream().filter(chartData1 -> "twc".equals(chartData1.getSensorType())).findAny().orElse(null);
                    //循环数据，然后去匹配天文潮
                    if (maxTowFTDZ!=null){
                        for (Data data : maxTowFTDZ) {
                            NBrep nBrep = new NBrep();
                            Data newData = new Data();
                            Data data1 = null;
                            if (TWCchartData != null) {
                                data1 = TWCchartData.getDatas().stream().filter(da -> da.getTM().equals(data.getTM())).findAny().orElse(null);
                            }
                           // newData.setTM(data.getTM());
                            nBrep.setTm(data.getTM());
                            //预报潮位
                           // newData.setValue(data.getValue());

                            if (data1 != null) {
                                //newData.setTwc(data1.getValue());
                                nBrep.setTwc(String.valueOf(data1.getValue()));
                                nBrep.setZs(df.format(data.getValue()));
                                nBrep.setFtdz(String.valueOf(df.format(data.getValue()+data1.getValue())));
                            }
                            //newData.setZs(Double.valueOf(df.format(newData.getValue() - newData.getTwc())));
                            nBreps.add(nBrep);
                            maxDatas.add(newData);
                        }
                    }
                    resultReport.setStnm(calResult.getStationName());
                    BDMS_ST_SENSORALARM_B sensoralarm_b = bdms_st_sensoralarm_bs.stream().filter(bdms_st_sensoralarm_b -> bdms_st_sensoralarm_b.getStcd().equals(stationCode)).findAny().orElse(null);
                    //System.out.println("sensoralarm_b"+sensoralarm_b);
                    //根据站码查询站点
                    if (sensoralarm_b != null) {
                        if (sensoralarm_b.getHistorymax() != null) {
                            resultReport.setLsData(sensoralarm_b.getHistorymax().replace(",", "\n"));
                        }
                        //xin
                        resultReport.setBcData(sensoralarm_b.getEnsure());
                        resultReport.setArmData(String.valueOf(sensoralarm_b.getAlarmvalue()));
                        //System.out.println(nbReport);
                    }
                    resultReport.setResults(nBreps);
                    resultReports.add(resultReport);
                }
                specialReport.setStringList(strings);
                specialReport.setResults(resultReports);
                list.add("2、沿海潮位预报");
                list.add("未来    天，我市处于天文潮大潮期。按目前台风预报路径及其变\n" +
                        "化趋势，南部三门湾海域预计高潮增水       ，象山东部海域\n" +
                        "    米，象山港海域增水         米，北部杭州湾海域         米，我市沿海潮位代表站最高潮位达到或略超警戒。");
                list.add("沿海潮位预报         单位：米");
                strtionCodes1.clear();
                strtionCodes1 = new ArrayList<>();
                //根据计算方案id去获取预报值
                strtionCodes1.add("70007711");
                strtionCodes1.add("70702791");
                strtionCodes1.add("70703400");
                strtionCodes1.add("70703800");
                strtionCodes1.add("70704600");
                bdms_st_sensoralarm_bs.clear();
                bdms_st_sensoralarm_bs = bdms_st_sensoralarm_bService.selectByStcd2(strtionCodes1);
                for (String stationCode : strtionCodes1) {
                    ResultReport resultReport = new ResultReport();
                    List<NBrep> nBreps = new ArrayList<>();
                    com.jhhc.utils.CalResult calResult = getDataUtil.getDataByCalSchemeIds(bdms_calculatescheme_m1.getPid(), strs, stationCode, 0, 0, 0, 0);
                    com.jhhc.utils.ChartData FTDZchartData = calResult.getCalSchemeInfos().get(0).getResults().stream().filter(chartData1 -> "tzzs".equals(chartData1.getSensorType())).findAny().orElse(null);
                    List<Data> maxTowFTDZ = getTopTwoData(FTDZchartData,forecastTime.substring(0,10));
                    List<Data> maxDatas = new ArrayList<>();
                    //  System.out.println("最大值f"+maxTowFTDZ);
                    com.jhhc.utils.ChartData TWCchartData = calResult.getBaseDatas().stream().filter(chartData1 -> "twc".equals(chartData1.getSensorType())).findAny().orElse(null);
                    //循环数据，然后去匹配天文潮
                    for (Data data : maxTowFTDZ) {
                        NBrep nBrep = new NBrep();
                        Data newData = new Data();
                        Data data1 = null;
                        if (TWCchartData != null) {
                            data1 = TWCchartData.getDatas().stream().filter(da -> da.getTM().equals(data.getTM())).findAny().orElse(null);
                        }
                       // newData.setTM(data.getTM());
                        nBrep.setTm(data.getTM());
                        //预报潮位
                        //newData.setValue(data.getValue());
                        nBrep.setFtdz(String.valueOf(data.getValue()));
                        if (data1 != null) {
                           // newData.setTwc(data1.getValue());
                            nBrep.setTwc(String.valueOf(data1.getValue()));
                            nBrep.setZs(String.valueOf(df.format(data.getValue() - data1.getValue())));
                        }
                        //newData.setZs(Double.valueOf(df.format(newData.getValue() - newData.getTwc())));
                        nBreps.add(nBrep);
                        maxDatas.add(newData);
                    }
                    BDMS_ST_SENSORALARM_B sensoralarm_b = bdms_st_sensoralarm_bs.stream().filter(bdms_st_sensoralarm_b -> bdms_st_sensoralarm_b.getStcd().equals(stationCode)).findAny().orElse(null);
                    //根据站码查询站点
                    if (sensoralarm_b != null) {
                        resultReport.setStnm(sensoralarm_b.getStnm());
                        if (sensoralarm_b.getHistorymax() != null) {
                            resultReport.setLsData(sensoralarm_b.getHistorymax().replace(",", "\n"));
                        }
                        resultReport.setBcData(sensoralarm_b.getEnsure());
                        resultReport.setArmData(String.valueOf(sensoralarm_b.getAlarmvalue()));
                    }
                    resultReport.setResults(nBreps);
                    resultReports2.add(resultReport);
                }
                specialReport.setStringList(list);
                specialReport.setReports2(resultReports2);
                bdmsProductResult.setGendat(uniqueId);
                bdmsProductResult.setCrttm(new Date());
                //实例化Document类的对象
                //加载Word
                String jsonString = JSON.toJSONString(specialReport);
                bdmsProductResult.setRemark(jsonString);
                int res = bdms_product_resultService.insert(bdmsProductResult);
                String ybsj =bdms_calculatescheme_m1.getDtmforecast();
                String tfid = bdms_calculatescheme_m1.getParams().split(",")[0];
                //根据预报时间获取所有计算方案
                List<BDMS_CALCULATESCHEME_M1> bdms_calculatescheme_m1s= bdms_calculatescheme_mService.selectShcemeByPidDate(bdmsProductResult.getPid(),tfid,ybsj,ybsj,null,"预报",null,null,null,null);
                for (BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m:bdms_calculatescheme_m1s){
                    if (bdms_calculatescheme_m.getCschemeid().equals(calSchemeId)){
                        bdms_calculatescheme_mService.updateGen(calSchemeId,1);
                    }else {
                        bdms_calculatescheme_mService.updateGen(bdms_calculatescheme_m.getCschemeid(),0);
                    }
                }
                System.out.println("插入条数为"+res);
                return "文档生成成功";
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public String GenSpecialReportNBnewAll(String calSchemeId, String infoId) {
        SpecialReportNB specialReport = new SpecialReportNB();
        List<String> strings = new ArrayList<>();
        List<ResultReport> resultReports = new ArrayList<>();
        List<ResultReport> resultReports2 = new ArrayList<>();
        List<String> list = new ArrayList<>();
        List<String> ssss = new ArrayList<>();
        ssss.add("70301400");
        ssss.add("70301200");
        ssss.add("70300800");
        //根据预报方案获取预报时间点
        BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m1 = bdms_calculatescheme_mService.selcalSchemeId(calSchemeId);
        if (bdms_calculatescheme_m1!=null) {
            BDMS_PRODUCT_RESULT bdmsProductResult = new BDMS_PRODUCT_RESULT();
            bdmsProductResult.setProdid(calSchemeId);
            bdmsProductResult.setInfoid(infoId);

            bdmsProductResult.setPid(bdms_calculatescheme_m1.getPid());
            List<String> stcds = new ArrayList<>();
            List<BDMS_ST_STBPRP_B> st_stbprp_bs = bdms_st_stbprp_bService.selectStationByProject(bdms_calculatescheme_m1.getPid());
            for (BDMS_ST_STBPRP_B st_stbprp_b : st_stbprp_bs) {
                stcds.add(st_stbprp_b.getStcd());
            }
            List<BDMS_ST_SENSORALARM_B> bdms_st_sensoralarm_bs = bdms_st_sensoralarm_bService.selectByStcd2(stcds);
            //获取预报时间点
            String forecastTime = bdms_calculatescheme_m1.getDtmforecast();
            String time2 = forecastTime.substring(5, 7) + "月"
                    + forecastTime.substring(8, 10) + "日" + forecastTime.substring(11, 13) + "时";
            UUID uuid = UUID.randomUUID();
            String uniqueId = uuid.toString();
            strings.add("水文站潮位研判");
            strings.add("宁波市水文站");
            strings.add("一、潮位研判");
            strings.add("研判结果：（根据" + time2 + "），中央台预报路径");
            strings.add("1、甬江干流潮位(水位)预报");
            //strings.add("根据气象预报，过程面雨量    到     毫米局部     毫米以上，考虑径流影响，预测甬江干流最高潮位       米，时间出现在  月  日  时左右，超保证，奉化江北渡站最高潮位      米，出现时间为  日  时左右，超保证接近历史最高。");
            strings.add("甬江干流潮位 (水位) 预报         单位：米");
            List<String> strs = new ArrayList<>();
            try {
                //根据计算方案id去获取预报值

                strs.add(calSchemeId);


                //BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m11 = bdms_calculatescheme_mService.selectShcemeByCalID(calSchemeId);
                for (String stationCode : ssss) {
                    ResultReport resultReport = new ResultReport();
                    List<NBrep> nBreps = new ArrayList<>();
                    com.jhhc.utils.CalResult calResult = getDataUtil.getDataByCalSchemeIds(bdms_calculatescheme_m1.getPid(), strs, stationCode, 0, 0, 0, 0);
                    com.jhhc.utils.ChartData FTDZchartData = calResult.getCalSchemeInfos().get(0).getResults().stream().filter(chartData1 -> "tzzs".equals(chartData1.getSensorType())).findAny().orElse(null);
                    List<Data> maxTowFTDZ = getTopTwoData(FTDZchartData,forecastTime.substring(0,10));
                    List<Data> maxDatas = new ArrayList<>();
                    //  System.out.println("最大值f"+maxTowFTDZ);
                    com.jhhc.utils.ChartData TWCchartData = calResult.getBaseDatas().stream().filter(chartData1 -> "twc".equals(chartData1.getSensorType())).findAny().orElse(null);
                    //循环数据，然后去匹配天文潮
                    if (maxTowFTDZ!=null){
                        for (Data data : maxTowFTDZ) {
                            NBrep nBrep = new NBrep();
                            Data newData = new Data();
                            Data data1 = null;
                            if (TWCchartData != null) {
                                data1 = TWCchartData.getDatas().stream().filter(da -> da.getTM().equals(data.getTM())).findAny().orElse(null);
                            }
                            // newData.setTM(data.getTM());
                            nBrep.setTm(data.getTM());
                            //预报潮位
                            // newData.setValue(data.getValue());
                            nBrep.setFtdz(String.valueOf(data.getValue()));
                            if (data1 != null) {
                                //newData.setTwc(data1.getValue());
                                nBrep.setTwc(String.valueOf(data1.getValue()));
                                nBrep.setZs(String.valueOf(df.format(data.getValue() - data1.getValue())));
                            }
                            //newData.setZs(Double.valueOf(df.format(newData.getValue() - newData.getTwc())));

                            nBreps.add(nBrep);
                            maxDatas.add(newData);
                        }
                    }
                    resultReport.setStnm(calResult.getStationName());
                    BDMS_ST_SENSORALARM_B sensoralarm_b = bdms_st_sensoralarm_bs.stream().filter(bdms_st_sensoralarm_b -> bdms_st_sensoralarm_b.getStcd().equals(stationCode)).findAny().orElse(null);
                    //根据站码查询站点
                    if (sensoralarm_b != null) {
                        if (sensoralarm_b.getHistorymax() != null) {
                            resultReport.setLsData(sensoralarm_b.getHistorymax().replace(",", "\n"));
                        }
                        //xin
                        resultReport.setBcData(sensoralarm_b.getEnsure());
                        resultReport.setArmData(String.valueOf(sensoralarm_b.getAlarmvalue()));
                        //System.out.println(nbReport);
                    }
                    resultReport.setResults(nBreps);
                    resultReports.add(resultReport);
                }
                specialReport.setStringList(strings);
                specialReport.setResults(resultReports);
                list.add("2、沿海潮位预报");
                list.add("未来    天，我市处于天文潮大潮期。按目前台风预报路径及其变\n" +
                        "化趋势，南部三门湾海域预计高潮增水       ，象山东部海域\n" +
                        "    米，象山港海域增水         米，北部杭州湾海域         米，我市沿海潮位代表站最高潮位达到或略超警戒。");
                list.add("沿海潮位预报         单位：米");
                for (String s : ssss) {
                    stcds.removeIf(value -> value.equals(s));
                }
//                strtionCodes1.clear();
//                strtionCodes1 = new ArrayList<>();
//                //根据计算方案id去获取预报值
//                strtionCodes1.add("70007711");
//                strtionCodes1.add("70702791");
//                strtionCodes1.add("70703400");
//                strtionCodes1.add("70703800");
//                strtionCodes1.add("70704600");

                List<BDMS_ST_SENSORALARM_B> bdms_st_sensoralarm_bs2 = bdms_st_sensoralarm_bService.selectByStcd2(stcds);
                for (String stationCode : stcds) {
                    ResultReport resultReport = new ResultReport();
                    List<NBrep> nBreps = new ArrayList<>();
                    com.jhhc.utils.CalResult calResult = getDataUtil.getDataByCalSchemeIds(bdms_calculatescheme_m1.getPid(), strs, stationCode, 0, 0, 0, 0);
                    com.jhhc.utils.ChartData FTDZchartData = calResult.getCalSchemeInfos().get(0).getResults().stream().filter(chartData1 -> "tz".equals(chartData1.getSensorType())).findAny().orElse(null);
                    List<Data> maxTowFTDZ = getTopTwoData(FTDZchartData,forecastTime.substring(0,10));
                    System.out.println(stationCode+":"+maxTowFTDZ);
                    List<Data> maxDatas = new ArrayList<>();
                    //  System.out.println("最大值f"+maxTowFTDZ);
                    com.jhhc.utils.ChartData TWCchartData = calResult.getBaseDatas().stream().filter(chartData1 -> "twc".equals(chartData1.getSensorType())).findAny().orElse(null);
                    //循环数据，然后去匹配天文潮
                    if (maxTowFTDZ!=null && maxTowFTDZ.size()>0) {
                        for (Data data : maxTowFTDZ) {
                            NBrep nBrep = new NBrep();
                            Data newData = new Data();
                            Data data1 = null;
                            if (TWCchartData != null) {
                                data1 = TWCchartData.getDatas().stream().filter(da -> da.getTM().equals(data.getTM())).findAny().orElse(null);
                            }
                            // newData.setTM(data.getTM());
                            nBrep.setTm(data.getTM());
                            //预报潮位
                            //newData.setValue(data.getValue());
                            nBrep.setFtdz(String.valueOf(data.getValue()));
                            if (data1 != null) {
                                // newData.setTwc(data1.getValue());
                                nBrep.setTwc(String.valueOf(data1.getValue()));
                                nBrep.setZs(String.valueOf(df.format(data.getValue() - data1.getValue())));
                            }
                            //newData.setZs(Double.valueOf(df.format(newData.getValue() - newData.getTwc())));

                            nBreps.add(nBrep);
                            maxDatas.add(newData);
                        }
                    }
                    BDMS_ST_SENSORALARM_B sensoralarm_b = bdms_st_sensoralarm_bs2.stream().filter(bdms_st_sensoralarm_b -> bdms_st_sensoralarm_b.getStcd().equals(stationCode)).findAny().orElse(null);
                    //根据站码查询站点
                    if (sensoralarm_b != null) {
                        resultReport.setStnm(sensoralarm_b.getStnm());
                        if (sensoralarm_b.getHistorymax() != null) {
                            resultReport.setLsData(sensoralarm_b.getHistorymax().replace(",", "\n"));
                        }
                        resultReport.setBcData(sensoralarm_b.getEnsure());
                        resultReport.setArmData(String.valueOf(sensoralarm_b.getAlarmvalue()));
                    }
                    resultReport.setResults(nBreps);
                    resultReports2.add(resultReport);
                }
                specialReport.setStringList(list);
                specialReport.setReports2(resultReports2);
                bdmsProductResult.setGendat(uniqueId);
                bdmsProductResult.setCrttm(new Date());
                //实例化Document类的对象
                //加载Word
                String jsonString = JSON.toJSONString(specialReport);
                bdmsProductResult.setRemark(jsonString);
                int res = bdms_product_resultService.insert(bdmsProductResult);
                String ybsj =bdms_calculatescheme_m1.getDtmforecast();
                String tfid = bdms_calculatescheme_m1.getParams().split(",")[0];
                //根据预报时间获取所有计算方案
                List<BDMS_CALCULATESCHEME_M1> bdms_calculatescheme_m1s= bdms_calculatescheme_mService.selectShcemeByPidDate(bdmsProductResult.getPid(),tfid,ybsj,ybsj,null,"预报",null,null,null,null);
                for (BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m:bdms_calculatescheme_m1s){
                    if (bdms_calculatescheme_m.getCschemeid().equals(calSchemeId)){
                        bdms_calculatescheme_mService.updateGen(calSchemeId,1);
                    }else {
                        bdms_calculatescheme_mService.updateGen(bdms_calculatescheme_m.getCschemeid(),0);
                    }
                }
                System.out.println("插入条数为"+res);
                return "文档生成成功";
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }
    //调用Python模型生成图片
    public JsonResult photoServer(String calSchemeId) {
        JsonResult jsonResult = new JsonResult();


        //根据计算方案编号获取计算方案信息
        BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m =  bdms_calculatescheme_mService.selectShcemeByCalID(calSchemeId);

        //如果不如空执行判断
        if (bdms_calculatescheme_m!=null){
            String forecastTime =  bdms_calculatescheme_m.getDtmforecast().replaceAll(" ","+");


            //
            int pid =  bdms_calculatescheme_m.getPid();
            List<String> calSchemeIds = new ArrayList<>();
            calSchemeIds.add(calSchemeId);
            //查询项目id下所有潮位站点
            List<BDMS_ST_STBPRP_B> stbprpBs =  bdms_st_stbprp_bService.selectStationByProject(pid);
            //stbprpBs过滤为空 过滤sttp等于TT
            List<BDMS_ST_STBPRP_B> st_stbprp_bs =  stbprpBs.stream().filter(st -> "TT".equals(st.getSttp())).collect(Collectors.toList());
            //创建站点集合对象
            List<String> stationCodes = new ArrayList<>();
            for (BDMS_ST_STBPRP_B st_stbprp_b : st_stbprp_bs) {
                stationCodes.add(st_stbprp_b.getStcd());
            }


            //根据方法中的参数去更新/mondel/photo/config.json下的json内容
            String currentDirectory = System.getProperty("user.dir");
            String dir = currentDirectory + File.separator+"model"+File.separator+"photo"+File.separator;
            String configDir = dir+"config.json";
//            String runDir = dir+"runGenPhoto";

            //创建文件夹生成文件夹

            String genDir = currentDirectory+File.separator+"photo"+File.separator;
            String path = genDir+calSchemeId+File.separator;
            File folder = new File(path);
            if (!folder.exists()) {
                folder.mkdirs(); // 使用mkdirs()方法可以递归创建多级文件夹
                System.out.println("文件夹已创建");
            } else {
                System.out.println("文件夹已存在");
            }
            try {
                String jsonString = new String(Files.readAllBytes(Paths.get(configDir)));
                JSONObject jsonObject =  JSONObject.parse(jsonString);

                // Update JSON content based on method parameters
                jsonObject.put("projectId", pid);

                jsonObject.put("calSchemeId",calSchemeId) ; // Convert List to JSON array
                JSONArray station = new JSONArray(stationCodes);
                jsonObject.put("stationCodes", station);
                jsonObject.put("twcDept",0);
                jsonObject.put("backDays", 2);
                jsonObject.put("address", path);
                jsonObject.put("serverType", serverType);
                // Write the updated JSON back to the file
                try (FileWriter file = new FileWriter(configDir)) {
                    file.write(jsonObject.toJSONString());
                    file.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ProcessBuilder processBuilder = new ProcessBuilder();
                //调用Python程序

                if ("liunx".equals(serverType)) {
                    String cmd = "cd " + dir + " && chmod +777 runGenPhoto && ./runGenPhoto";
                    processBuilder.command("sh", "-c", cmd);
                    List<String> command = processBuilder.command();
                    String fullCommand = String.join(" ", command);
                    System.out.println(fullCommand);
                }else {
                    processBuilder.command("python ", dir+"genPhoto.py");
                }


                // 设置工作目录（可选）
                processBuilder.directory(new File(dir));

                // 启动进程并执行Python脚本
                Process process = processBuilder.start();

                // 获取Python脚本的输出（如果有）
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }

                boolean finished = process.waitFor(10, TimeUnit.SECONDS);
                System.out.println(finished);
                if (finished) {
                    // 进程已经终止
                    int exitValue = process.exitValue();
                    System.out.println("exitCode"+exitValue);
                    if (exitValue ==0) {
                        jsonResult.setStatusCode(200);
                        jsonResult.setSucceeded(true);
                        jsonResult.setData("图片生成成功");
                        jsonResult.setRemark("请求成功");
                    }else {
                        jsonResult.setStatusCode(201);
                        jsonResult.setSucceeded(true);
                        jsonResult.setData("请求失败");
                        jsonResult.setRemark("图片生成异常");
                    }
                } else {
                    process.destroy(); // 终止进程
                    jsonResult.setStatusCode(201);
                    jsonResult.setSucceeded(true);
                    jsonResult.setData("请求失败");
                    jsonResult.setRemark("图片生成超时");
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            jsonResult.setStatusCode(201);
            jsonResult.setSucceeded(true);
            jsonResult.setData("请求失败");
            jsonResult.setRemark("此计算方案不存在");
        }



        return  jsonResult;
    }

    //读取图片
    public JsonResult readImage(String calSchemeId) throws  Exception{
        //根据计算方案编号获取计算方案信息
        BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m =  bdms_calculatescheme_mService.selectShcemeByCalID(calSchemeId);
        JsonResult jsonResult = new JsonResult();
        //如果不如空执行判断
        if (bdms_calculatescheme_m!=null) {
            String forecastTime = bdms_calculatescheme_m.getDtmforecast().replaceAll(" ", "+");
            String endTime = bdms_calculatescheme_m.getDtmend().replaceAll(" ", "+");
            String path = GetInformTxtUtil.getCourseFile() + File.separator + "photo" + File.separator + calSchemeId + File.separator;
            List<String> base64s = new ArrayList<>();
            File dirFile = new File(path);
            File[] files = dirFile.listFiles();
            DownloadImages downloadImages = new DownloadImages();
            //访问请求获取到图片
            // 发送第一个GET请求
            String firstUrl = "http://180.96.23.207:2109/Weathers/Picture/GetPictureList?productSource=%E4%B8%AD%E5%A4%AE%E6%B0%94%E8%B1%A1%E5%8F%B0&productType=%E5%8F%B0%E9%A3%8E%E8%B7%AF%E5%BE%84%E9%A2%84%E6%8A%A5&pictureType=%E5%8F%B0%E9%A3%8E%E8%B7%AF%E5%BE%84%E9%A2%84%E6%8A%A5%E5%9B%BE2&startTime=" + forecastTime + "&endTime=" + endTime;
            System.out.println(firstUrl);
            CloseableHttpClient httpClient = HttpClients.createDefault();  //http请求
            HttpGet httpPost = new HttpGet(firstUrl);
            httpPost.addHeader("Content-Type", "application/json");
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity);
            JSONObject json = JSON.parseObject(responseContent);
            JSONObject json1 = json.getJSONObject("data");
            // 获取pictureList数组
            JSONArray pictureList = json1.getJSONArray("pictureList");
            if (pictureList!=null) {
                // 获取第一个元素
                JSONObject picture = pictureList.getJSONObject(0);
                // 获取absolutepath和relativepath的值
                String absolutepath = picture.getString("absolutepath");
                String relativepath = picture.getString("relativepath");
                String encodedURL = URLEncoder.encode(relativepath);
                //创建请求获取到图片
                String url = "http://180.96.23.207:2109/Weathers/Picture/GetSingle?absolutepath=" + absolutepath + "&relativepath=" + encodedURL;
                HttpGet httpGet = new HttpGet(url);
                httpGet.addHeader("Content-Type", "application/json");
                CloseableHttpResponse response1 = httpClient.execute(httpGet);
                HttpEntity entity1 = response1.getEntity();
                String image = EntityUtils.toString(entity1);
                JSONObject jsonImage = JSON.parseObject(image);
                String images = jsonImage.getString("data");
                downloadImages.setTyphoonImage(images);
            }
            if (files != null) {
                for (File file : files) {
                    if (file.isFile()) {
                        String base64 = null;
                        try {
                            base64 = Base64.getEncoder().encodeToString(FileUtils.readFileToByteArray(file));
                            base64s.add(base64);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }

                    }
                }
                downloadImages.setTideImages(base64s);
            }
            if (downloadImages.getTyphoonImage()!=null || downloadImages.getTideImages()!=null){
                jsonResult.setStatusCode(200);
                jsonResult.setSucceeded(true);
                jsonResult.setData(downloadImages);
                jsonResult.setRemark("请求成功");
            }
            else {
                jsonResult.setStatusCode(201);
                jsonResult.setSucceeded(true);
                jsonResult.setData("未获取到此方案生成图片信息");
                jsonResult.setRemark("请求成功");
            }
        }else {
            jsonResult.setStatusCode(201);
            jsonResult.setSucceeded(true);
            jsonResult.setData("请求失败");
            jsonResult.setRemark("此计算方案不存在");
        }
        return  jsonResult;
    }


    // 辅助方法：解析日期字符串为LocalDate
    private static LocalDate parseLocalDate(String dateString) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(dateString, formatter);
        return dateTime.toLocalDate();
    }
    //第一高潮第二高潮
    public List<Data> getTopTwoData(com.jhhc.utils.ChartData chartData,String forecastTime) {
        if (chartData!=null) {
            chartData.getDatas().removeIf(obj -> obj.getTM().contains(forecastTime));
            chartData.getDatas().removeIf(obj -> obj.getHltdmk()!=null && obj.getHltdmk()>2);
            // 按照tm属性进行分组   &&
            Map<LocalDate, List<Data>> groupedByDate = chartData.getDatas().stream()
                    .collect(Collectors.groupingBy(obj -> parseLocalDate(obj.getTM())));
            // 对每个日期的数据进行处理，获取每天的两个最大值的对象
            Map<LocalDate, List<Data>> topTwoByDate = new HashMap<>();
            for (Map.Entry<LocalDate, List<Data>> entry : groupedByDate.entrySet()) {
                List<Data> topTwo = entry.getValue().stream()
                        .sorted(Comparator.comparingDouble(Data::getValue).reversed())
                        .limit(2)
                        .collect(Collectors.toList());
                topTwoByDate.put(entry.getKey(), topTwo);
            }
            // 对topTwoByDate进行排序，并选择前三天的数据
//            List<LocalDate> sortedDates = topTwoByDate.keySet().stream()
//                    .sorted()
//                    .collect(Collectors.toList());
            // 对topTwoByDate进行排序，并选择前三天的数据
            List<LocalDate> firstThreeDays = topTwoByDate.keySet().stream()
                    .sorted()
                    .collect(Collectors.toList());

            List<LocalDate> sortedDates = firstThreeDays.stream()
                    .limit(3)
                    .collect(Collectors.toList());
            // 如果数据源中的日期少于三天，则直接选择全部日期
            if (sortedDates.size() <= 3) {
                sortedDates = sortedDates.subList(0, sortedDates.size());
            } else {
                sortedDates = sortedDates.subList(sortedDates.size() - 3, sortedDates.size());
            }

            List<Data> datas  =sortedDates.stream()
                    .flatMap(date -> topTwoByDate.get(date).stream())
                    .collect(Collectors.toList());
            datas.sort(Comparator.comparing(Data::getTM));
            // 获取最后三天的数据
            return datas;
        }
       return null;
    }
    public List<Data> getTopTwoData2(com.jhhc.utils.ChartData chartData) {
        if (chartData!=null) {

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//            for (Data data : chartData.getDatas()) {
//                System.out.println("va"+data);
//            }
            Map<LocalDate, List<Data>> groupedData = chartData.getDatas().stream()
                    .collect(Collectors.groupingBy(data -> LocalDateTime.parse(data.getTM(), formatter).toLocalDate()));
            List<List<Data>> topTwoGroups = groupedData.values().stream()
                    .map(group -> group.stream()
                            .sorted(Comparator.comparingDouble(Data::getValue).reversed())
                            .limit(1)
                            .collect(Collectors.toList()))
                    .collect(Collectors.toList());





            List<Data> maxTwo = new ArrayList<>();
//            for (List<Data> group : topTwoGroups) {
//                maxTwo.addAll(group);
//            }
//            maxTwo.sort(Comparator.comparing(Data::getTM));

//            System.out.println("max:"+firstThree);




        Data maxData = maxTwo.stream().max(Comparator.comparing(Data::getValue)).orElse(null);
        int maxAgeIndex = maxTwo.indexOf(maxData);
        Data maxData2 = null;
        if (maxAgeIndex > 0) {
            maxData2 = maxTwo.get(maxAgeIndex - 1);
        }else {
            maxData2 = maxTwo.get(maxAgeIndex + 1);
        }
        maxTwo.clear();
        maxTwo.add(maxData);
        maxTwo.add(maxData2);


            maxTwo.stream().sorted(Comparator.comparing(Data::getValue).reversed())
                .limit(2)
                .collect(Collectors.toList());
            List<Data> firstThree = maxTwo.stream().limit(3).collect(Collectors.toList());
            return firstThree ;
        }
        return null;
    }
    public List<Data> getValueModel(String fileName) throws Exception {
        String filePath = "/root/anaconda3/storm-surge/";
        String path = filePath+fileName;
        List<Data> datas = new ArrayList<>();
        BufferedReader br = new BufferedReader(new FileReader(path));
        String line;
        while ((line = br.readLine()) != null) {
            Data data = new Data();
            String[] dateParts = line.split(" ");
            data.setStcd(dateParts[0]);
            String formattedDate = String.format("%s-%02d-%02d %02d:%02d:%02d", dateParts[1],
                    Integer.parseInt(dateParts[2]), Integer.parseInt(dateParts[3]),
                    Integer.parseInt(dateParts[4]), 0, 0);
            data.setTM(formattedDate);
            data.setValue(Double.valueOf(dateParts[5]));
            datas.add(data);
        }
        return datas;
    }


    //修改报表数据
    private static String getSixDigitValue(String longString, int inputNumber) {

        int startIndex = (inputNumber - 1) * 6;
        int endIndex = startIndex + 6;
//        System.out.println(longString);
//        System.out.println(longString.length());
//        System.out.println(startIndex);
//        System.out.println(endIndex);
        if (startIndex >= 0 && endIndex <= longString.length()) {
            return longString.substring(startIndex, endIndex);
        } else {
            return "Invalid input number";
        }
    }
    private static String modifySixDigitValue(String longString, int inputNumber, String newValue) {
        int startIndex = (inputNumber - 1) * 6;
        int endIndex = startIndex + 6;

        if (startIndex >= 0 && endIndex <= longString.length()) {
            String originalValue = longString.substring(startIndex, endIndex);
            return longString.replace(originalValue, newValue);
        } else {
            return longString;
        }
    }
    public JsonResult updateData(String calid, String stationCode,String value) {
        JsonResult jsonResult = new JsonResult();
        // 获取方案信息
        BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m1 = bdms_calculatescheme_mService.selcalSchemeId(calid);
        if (bdms_calculatescheme_m1 != null) {

            BDMS_FBC_RESULT_P bdms_fbc_result_p = new BDMS_FBC_RESULT_P();
            bdms_fbc_result_p.setCschemeid(calid);
            bdms_fbc_result_p.setPtkey(stationCode);
            bdms_fbc_result_p.setRemark(value);

            //_p入库 26
            int res  = bdms_fbc_result_pService.update(bdms_fbc_result_p);
            bdms_calculatescheme_mService.updateGen(bdms_calculatescheme_m1.getCschemeid(),0);
            System.out.println(res);
            if (res>0){
                jsonResult.setStatusCode(200);
                jsonResult.setSucceeded(true);
                jsonResult.setData("更新数据成功");
                jsonResult.setRemark("请求成功");
            }else {
                jsonResult.setStatusCode(201);
                jsonResult.setSucceeded(true);
                jsonResult.setData("更新失败");
                jsonResult.setRemark("数据更新异常");
            }


        }else {
            jsonResult.setStatusCode(201);
            jsonResult.setSucceeded(true);
            jsonResult.setData("更新失败");
            jsonResult.setRemark("未获取到相关方案信息");
        }

        return jsonResult;
    }

    public String getTimeChar(String tm) {
        if (tm.charAt(0) == '0') {
            return tm.substring(1, 2);
        }
        return tm;
    }

    public  String fileDel( String filePath ){

        File file = new File(filePath);
        // 检查文件是否存在
        if (file.exists()) {
            // 如果存在则删除文件
            if (file.delete()) {
                return "已删除文件";
            } else {
                return "无法删除现有文件";
            }
        }else {
            return "文件不存在";
        }

    }


    //生成天文潮文件
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat format_1 = new SimpleDateFormat("yyyy/MM/dd HH:mm");
    public boolean  genTdzTxt(List<ST_TIDE_R> st_tide_rList) throws Exception {
        fileDel("/root/anaconda3/storm-surge/st_tide_r.txt");
        if (st_tide_rList.size() == 48) {
            FileWriter writer = new FileWriter("/root/anaconda3/storm-surge/st_tide_r.txt");
            for (ST_TIDE_R st_tide_r : st_tide_rList) {
                String stcd = st_tide_r.getStcd();
                String tm = format_1.format(format.parse(st_tide_r.getTm()));
                String year = tm.substring(0, 4);
                String month = getTimeChar(tm.substring(5, 7));
                String day = getTimeChar(tm.substring(8, 10));
                String hour = tm.substring(11, 13);
                String date = year + "/" + month + "/" + day + " " + hour + ":00";
                double tdz = st_tide_r.getTdz();
                String[] arrayOfString = {stcd, date, String.format(String.valueOf(tdz))};
                writer.write(String.format("%s  %s  %s%n", arrayOfString[0], arrayOfString[1], arrayOfString[2]));
            }
            writer.close();
            return true;
        }else {
            return false;
        }
    }

    public void genTwcTxt(List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFs) throws Exception {
        fileDel("/root/anaconda3/storm-surge/bdms_st_astrotd_f.txt");
        FileWriter writerf = new FileWriter("/root/anaconda3/storm-surge/bdms_st_astrotd_f.txt");
        for (BDMS_ST_ASTROTD_F bdmsStAstrotdF : bdmsStAstrotdFs) {
            if (bdmsStAstrotdF.getHltdmk() == 0) {
                String stcd = bdmsStAstrotdF.getStcd();
                String tm = format_1.format(format.parse(bdmsStAstrotdF.getYmdh()));
                String year = tm.substring(0, 4);
                String month = getTimeChar(tm.substring(5, 7));
                String day = getTimeChar(tm.substring(8, 10));
                String hour = getTimeChar(tm.substring(11, 13));
                String date = year + "/" + month + "/" + day + " " + hour + ":00";
                double tdz = bdmsStAstrotdF.getFtdz();
                String[] arrayOfString = { stcd, date, String.format(String.valueOf(tdz)), String.valueOf(0), String.valueOf(0) };
                writerf.write(String.format("%s  %s  %s  %s  %s%n", arrayOfString[0], arrayOfString[1], arrayOfString[2], arrayOfString[3], arrayOfString[4]));
            }
        }
        writerf.close();

    }


    //解析文件入库
    public void     analysisFile(String fileName,String calId) throws Exception {
        List<BDMS_FBC_RESULT_P> bdms_fbc_result_pList = new ArrayList<>();
        //解析文件入库
        Map<String, List<Data>> groupedByStcd = getValueModel(fileName).stream().collect(Collectors.groupingBy(Data::getStcd));
        groupedByStcd.forEach((stcd, datas) -> {
            StringBuilder dataValues = new StringBuilder();
            BDMS_FBC_RESULT_P bdms_fbc_result_p = new BDMS_FBC_RESULT_P();
            bdms_fbc_result_p.setCschemeid(calId);
            switch (fileName){
                case "tide_output.dat":
                    bdms_fbc_result_p.setDttp(2);
                    break;
                case "Stormtide_output.dat":
                    bdms_fbc_result_p.setDttp(1);
                    break;
                case "surge_output.dat":
                    bdms_fbc_result_p.setDttp(0);
                    break;
            }

            if ("1110".equals(stcd)) {
                bdms_fbc_result_p.setPtkey("70703400");
            }
            if ("1919".equals(stcd)) {
                bdms_fbc_result_p.setPtkey("70301400");
            }
            for (Data data : datas) {
                String formattedNumber = String.format("%06d", (int) (data.getValue() * 100));
                dataValues.append(formattedNumber);
            }
            bdms_fbc_result_p.setDtvalues(dataValues.toString());
            bdms_fbc_result_pList.add(bdms_fbc_result_p);
            System.out.println(bdms_fbc_result_p);

        });
        //文件入库
        int insert= bdms_fbc_result_pService.batchInsert(bdms_fbc_result_pList);
        System.out.println("入库条数"+insert);
    }

    //调用智能预报模型
//    public  String intelligentForecast(int projectId,String typhoonId, String forecastTime,String ModelId,String forecastDept, double xiShu ,String modelType) throws Exception {
//        List<String> stationCodes = new ArrayList<>();
//        stationCodes.add("70301400");
//        stationCodes.add("70703400");
//        Calendar calendar = new GregorianCalendar();
//        Date time = format.parse(forecastTime);
//        calendar.setTime(time);
//        calendar.add(Calendar.HOUR_OF_DAY, -24);
//        String startTime = format.format(calendar.getTime());
//        calendar.setTime(time);
//        calendar.add(Calendar.DATE,1);
//        String dtmEnd =format.format(calendar.getTime());
//        List<BDMS_ST_SENSOR_B> bdms_st_sensor_bs = this.bdms_st_sensor_bService.selectBySTCD29(Integer.valueOf(projectId),stationCodes);
//        List<String> tdzStationCodes = new ArrayList<>();
//        for (BDMS_ST_SENSOR_B bdms_st_sensor_b : bdms_st_sensor_bs) {
//            String tdzDataCode = bdms_st_sensor_b.getDatacode();
//            tdzStationCodes.add(tdzDataCode);
//        }
//        //计算方案入库
//        BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m = new BDMS_CALCULATESCHEME_M1();
//        //生成唯一码
//        String calId = String.valueOf(UUID.randomUUID());
//        bdms_calculatescheme_m.setCschemeid(calId);
//        //预报时间 forecasttime
//        bdms_calculatescheme_m.setDtmforecast(forecastTime);
//        //结束时间 forecasttime +1day
//        bdms_calculatescheme_m.setDtmend(dtmEnd);
//        //项目id
//        bdms_calculatescheme_m.setPid(projectId);
//        //userID
//        bdms_calculatescheme_m.setUserid("WEB");
//        //预报部门
//        //bdms_calculatescheme_m.setFstation("WEB");
//        //操作时间
//        String dtmCalCulate =format.format(new Date());
//        bdms_calculatescheme_m.setFschemeid(forecastDept);
//        bdms_calculatescheme_m.setCalinterval(0);
//        bdms_calculatescheme_m.setParschemeid(0);
//        bdms_calculatescheme_m.setDtmcalculate(dtmCalCulate);
//        //模型idsudo systemctl restart docker.service
//        bdms_calculatescheme_m.setMdid(ModelId);
//        //编号 部门 系数
//        bdms_calculatescheme_m.setParams(typhoonId+","+forecastDept+","+xiShu);
//        //获取数据库数据唯一操作
//        List<ST_TIDE_R> st_tide_rs = this.st_tide_rService.selectByOneStcd(tdzStationCodes, startTime, forecastTime);
//        List<ST_TIDE_R> st_tide_rList = st_tide_rs.stream().filter(sT_TIDE_R -> "00".equals(sT_TIDE_R.getTm().substring(14, 16))).collect(Collectors.toList());
//        //天文潮
//        calendar.setTime(format.parse(forecastTime));
//        calendar.add(Calendar.DATE, 1);
//        String endTime = format.format(calendar.getTime());
//        List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFs = this.bdms_st_astrotd_fService.selectByOnwFtdz(stationCodes, startTime, endTime, 0);
//        //当modelType==2  天文潮矫正
//        if ("2".equals(modelType)){
//            //判断是否数据完整
//            //生成实测txt
//            if (genTdzTxt(st_tide_rList)) {
//                //生成天文潮txt
//                genTwcTxt(bdmsStAstrotdFs);
//                //驱动程序然后文件入库
//                System.out.println(fileDel("/root/anaconda3/storm-surge/tide_output.dat"));
//                ProcessBuilder builder = new ProcessBuilder("/bin/bash", "/root/anaconda3/tide_pre.sh");
//                builder.directory(new File("/root/anaconda3"));
//                Process process = builder.start();
//                process.waitFor();
//                //调用解析入库方法
//                analysisFile("tide_output.dat",calId);
//                bdms_calculatescheme_m.setState("3");
//            }else {
//                List<BDMS_FBC_RESULT_P> bdms_fbc_result_pList = new ArrayList<>();
//                bdms_calculatescheme_m.setState("2");
//                //不调用生成文件的驱动
//                //返回库里的天文潮值
//                //读取库里的天文潮并入库  开始时间结束时间站点
//                List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFList = bdms_st_astrotd_fService.selectByOnwFtdz(stationCodes, forecastTime, dtmEnd, 0);
//                //根据站码分组
//                Map<String, List<BDMS_ST_ASTROTD_F>> groupedByStcd = bdmsStAstrotdFList.stream()
//                        .collect(Collectors.groupingBy(BDMS_ST_ASTROTD_F::getStcd));
//                // 打印分组结果
//                groupedByStcd.forEach((stcd, bdmsDatas) -> {
//                    //  List<Data> dataList = new ArrayList<>();
//                    //创建入库
//                    BDMS_FBC_RESULT_P bdms_fbc_result_p = new BDMS_FBC_RESULT_P();
//                    bdms_fbc_result_p.setCschemeid(calId);
//                    bdms_fbc_result_p.setPtkey(stcd);
//                    bdms_fbc_result_p.setDttp(2);
//                    StringBuilder dataValues = new StringBuilder();
//                    for (BDMS_ST_ASTROTD_F bdms_st_astrotd_f:bdmsDatas){
//                        //读取数据转成 6位格式
//                        String formattedNumber = String.format("%06d", (int) (bdms_st_astrotd_f.getFtdz() * 100));
//                        dataValues.append(formattedNumber);
//                    }
//                    bdms_fbc_result_p.setDtvalues(dataValues.toString());
//                    bdms_fbc_result_pList.add(bdms_fbc_result_p);
//                    System.out.println(bdms_fbc_result_p);
//                });
//                int insert=  bdms_fbc_result_pService.batchInsert(bdms_fbc_result_pList);
//                System.out.println("-p入库成功条数："+insert);
//            }
//            //计算方案入库
//
//        }else {
//            //增水
//            //生成nhup1和台风文件
//            fileDel("/root/anaconda3/storm-surge/nhup1.dat");
//            FileWriter nhup1 = new FileWriter("/root/anaconda3/storm-surge/nhup1.dat");
//            calendar.setTime(format.parse(forecastTime));
//            calendar.add(Calendar.HOUR,  -11);
//            String fstart = format.format(calendar.getTime());
//            String syear = fstart.substring(0, 4);
//            String smonth = getTimeChar(fstart.substring(5, 7));
//            String sday = getTimeChar(fstart.substring(8, 10));
//            String shour = getTimeChar(fstart.substring(11, 13));
//            String[] data = { syear, smonth, sday, shour };
//            nhup1.write(String.format("%s  %s  %s  %s%n", data[0], data[1], data[2], data[3]));
//            String esyear = endTime.substring(0, 4);
//            String esmonth = getTimeChar(endTime.substring(5, 7));
//            String esday = getTimeChar(endTime.substring(8, 10));
//            String eshour = getTimeChar(endTime.substring(11, 13));
//            String[] edata = { esyear, esmonth, esday, eshour };
//            nhup1.write(String.format("%s  %s  %s  %s%n", edata[0], edata[1], edata[2], edata[3]));
//            nhup1.close();
//            //生成台风数据文件
//            //根据台风id 开始时间结束时间获取台风数据
//            List<TfData> tfDatas = new ArrayList<>();
//            List<BDMS_FBC_TFPATH_R> bdms_fbc_tfpath_rs = this.bdms_fbc_tfpath_rService.searchAllByTfid(typhoonId, fstart, forecastTime);
//            fileDel("/root/anaconda3/storm-surge/tfpath.dat");
//            FileWriter tfPath = new FileWriter("/root/anaconda3/storm-surge/tfpath.dat");
//            for (BDMS_FBC_TFPATH_R fbc_tfpath_r : bdms_fbc_tfpath_rs) {
//                String tm = format.format(fbc_tfpath_r.getYmdhm());
//                TfData tfData = new TfData();
//                String year = tm.substring(0, 4);
//                String month = getTimeChar(tm.substring(5, 7));
//                String day = getTimeChar(tm.substring(8, 10));
//                String hour = getTimeChar(tm.substring(11, 13));
//                String lttd = String.valueOf(fbc_tfpath_r.getLttd());
//                String lgtd = String.valueOf(fbc_tfpath_r.getLgtd());
//                int pressure = fbc_tfpath_r.getPressure();
//                int moveSpeed = fbc_tfpath_r.getMaxspeed();
//                tfData.setYear(year);
//                tfData.setMonth(month);
//                tfData.setDay(day);
//                tfData.setHour(hour);
//                tfData.setLttd(lttd);
//                tfData.setLgtd(lgtd);
//                tfData.setPressure(pressure);
//                tfData.setMoveSpeed(moveSpeed);
//                tfDatas.add(tfData);
//            }
//            List<BDMS_FBC_TFPATH_F> bdms_fbc_tfpath_fs = this.bdms_fbc_tfpath_fService.selectBytfid(typhoonId, forecastDept, forecastTime, endTime);
//            List<BDMS_FBC_TFPATH_F> uniqueObjects = new ArrayList<>(((Map)bdms_fbc_tfpath_fs.stream().collect(Collectors.toMap(BDMS_FBC_TFPATH_F::getRealtm, Function.identity(), (o1, o2) -> o1))).values());
//            List<BDMS_FBC_TFPATH_F> uniqueObjects1 = new ArrayList<>(((Map)uniqueObjects.stream().collect(Collectors.toMap(BDMS_FBC_TFPATH_F::getForecasttm, Function.identity(), (o1, o2) -> o1))).values());
//            uniqueObjects1.sort(Comparator.comparing(BDMS_FBC_TFPATH_F::getRealtm));
//            for (BDMS_FBC_TFPATH_F bdms_fbc_tfpath_f : uniqueObjects1) {
//                String tm = format.format(bdms_fbc_tfpath_f.getRealtm());
//                if (format.parse(fstart).getTime() <= bdms_fbc_tfpath_f.getRealtm().getTime()) {
//                    TfData tfData = new TfData();
//                    String year = tm.substring(0, 4);
//                    String month = getTimeChar(tm.substring(5, 7));
//                    String day = getTimeChar(tm.substring(8, 10));
//                    String hour = getTimeChar(tm.substring(11, 13));
//                    String lttd = String.valueOf(bdms_fbc_tfpath_f.getLttd());
//                    String lgtd = String.valueOf(bdms_fbc_tfpath_f.getLgtd());
//                    int pressure = bdms_fbc_tfpath_f.getPressure();
//                    int moveSpeed = bdms_fbc_tfpath_f.getMaxspeed();
//                    tfData.setYear(year);
//                    tfData.setMonth(month);
//                    tfData.setDay(day);
//                    tfData.setHour(hour);
//                    tfData.setLttd(lttd);
//                    tfData.setLgtd(lgtd);
//                    tfData.setPressure(pressure);
//                    tfData.setMoveSpeed(moveSpeed);
//                    tfDatas.add(tfData);
//                }
//            }
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//            LocalDateTime st = LocalDateTime.parse(fstart, formatter);
//            LocalDateTime et = LocalDateTime.parse(endTime, formatter);
//            Duration duration = Duration.between(st, et);
//            long hours = duration.toHours();
//            List<TfData> tfDatas1 = new ArrayList<>();
//            int i;
//            for (i = 0; i <= hours; i++) {
//                TfData tfData = new TfData();
//                calendar.setTime(format.parse(fstart));
//                calendar.add(10, i);
//                String year = getTimeChar(format.format(calendar.getTime()).substring(0, 4));
//                String month = getTimeChar(format.format(calendar.getTime()).substring(5, 7));
//                String day = getTimeChar(format.format(calendar.getTime()).substring(8, 10));
//                String hour = getTimeChar(format.format(calendar.getTime()).substring(11, 13));
//                tfData.setYear(year);
//                tfData.setMonth(month);
//                tfData.setDay(day);
//                tfData.setHour(hour);
//                tfDatas1.add(tfData);
//            }
//            for (TfData tfData1 : tfDatas1) {
//                for (TfData tfData : tfDatas) {
//                    if (tfData1.getYear().equals(tfData.getYear()) && tfData1.getMonth().equals(tfData.getMonth()) && tfData1
//                            .getDay().equals(tfData.getDay()) && tfData1.getHour().equals(tfData.getHour())) {
//                        tfData1.setLgtd(tfData.getLgtd());
//                        tfData1.setLttd(tfData.getLttd());
//                        tfData1.setMoveSpeed(tfData.getMoveSpeed());
//                        tfData1.setPressure(tfData.getPressure());
//                    }
//                }
//            }
//            for (i = 0; i < tfDatas1.size(); i++) {
//                if (tfDatas1.get(i).getLttd() == null) {
//                    int j = i + 1;
//                    while (j < tfDatas1.size() && tfDatas1.get(j).getLttd() == null) {
//                        j++;
//                    }
//                    if (j < tfDatas1.size()) {
//                        tfDatas1.get(i).setLgtd(tfDatas1.get(j).getLgtd());
//                        tfDatas1.get(i).setLttd(tfDatas1.get(j).getLttd());
//                        tfDatas1.get(i).setMoveSpeed(tfDatas1.get(j).getMoveSpeed());
//                        tfDatas1.get(i).setPressure(tfDatas1.get(j).getPressure());
//                    } else {
//                        int k = i - 1;
//                        while (k >= 0 && tfDatas1.get(k).getLttd() == null) {
//                            k--;
//                        }
//                        if (k >= 0) {
//                            tfDatas1.get(i).setLgtd(tfDatas1.get(k).getLgtd());
//                            tfDatas1.get(i).setLttd(tfDatas1.get(k).getLttd());
//                            tfDatas1.get(i).setMoveSpeed(tfDatas1.get(k).getMoveSpeed());
//                            tfDatas1.get(i).setPressure(tfDatas1.get(k).getPressure());
//                        }
//                    }
//                }
//                tfPath.write(String.format("%s  %s  %s  %s   %s  %s   %s  %s%n", tfDatas1.get(i).getYear(), ((TfData)tfDatas1
//                        .get(i)).getMonth(), tfDatas1.get(i).getDay(), tfDatas1.get(i).getHour(), ((TfData)tfDatas1.get(i)).getLttd(), ((TfData)tfDatas1
//                        .get(i)).getLgtd(), tfDatas1.get(i).getPressure(), tfDatas1.get(i).getMoveSpeed()));
//            }
//            tfPath.close();
//            //根据生成的台风路径数据文件已经预报时间点文件 去生成文件
//            System.out.println(fileDel("/root/anaconda3/storm-surge/surge_output.dat"));
//            ProcessBuilder builder2 = new ProcessBuilder("/bin/bash", "/root/anaconda3/surge_pre.sh");
//            builder2.directory(new File("/root/anaconda3"));
//            Process process2 = builder2.start();
//            process2.waitFor();
//            System.out.println("增水文件ok");
//            //解析增水文件  入库
//            analysisFile("surge_output.dat",calId);
//            //生成实测和天文潮 调用获取风暴潮位模型
//            System.out.println(fileDel("/root/anaconda3/storm-surge/Stormtide_output.dat"));
//            genTwcTxt(bdmsStAstrotdFs);
//            String bash;
//            if (genTdzTxt(st_tide_rList)){
//                bash = "/root/anaconda3/storm_tide_pre.sh";
//            }else {
//                bash = "/root/anaconda3/storm_tide_pre_no_enough.sh";
//            }
//            System.out.println("调用的模型："+bash);
//            ProcessBuilder builder3 = new ProcessBuilder("/bin/bash", bash);
//            builder3.directory(new File("/root/anaconda3"));
//            Process process3 = builder3.start();
//            process3.waitFor();
//            //生成文件后解析文件
//            analysisFile("Stormtide_output.dat",calId);
//        }
//        bdms_calculatescheme_mService.insertBdmsCalculateschemeM(bdms_calculatescheme_m);
//        return calId;
//
//
//
//
//
//
//
//
//
//
//
//
//
////
////        //脚本执行结束 当脚本执行结束后 计算方案入库
////        BDMS_CALCULATESCHEME_M1 bdms_calculatescheme_m = new BDMS_CALCULATESCHEME_M1();
////        //生成唯一码
////        String calId = String.valueOf(UUID.randomUUID());
////        bdms_calculatescheme_m.setCschemeid(calId);
////        //预报时间 forecasttime
////
////        bdms_calculatescheme_m.setDtmforecast(forecastTime);
////        //结束时间 forecasttime +1day
////        bdms_calculatescheme_m.setDtmend(endTime);
////        //项目id
////        bdms_calculatescheme_m.setPid(projectId);
////        //userID
////        bdms_calculatescheme_m.setUserid("WEB");
////        //预报部门
////        //bdms_calculatescheme_m.setFstation("WEB");
////        //操作时间
////        String dtmCalCulate =format.format(new Date());
////        bdms_calculatescheme_m.setFschemeid(forecastDept);
////        bdms_calculatescheme_m.setCalinterval(0);
////        bdms_calculatescheme_m.setParschemeid(0);
////        bdms_calculatescheme_m.setDtmcalculate(dtmCalCulate);
////        //模型idsudo systemctl restart docker.service
////        bdms_calculatescheme_m.setMdid(ModelId);
////        //编号 部门 系数
////        bdms_calculatescheme_m.setParams(typhoonId+","+forecastDept+","+xiShu);
////        try {
////            System.out.println(fileDel("/root/anaconda3/storm-surge/surge_output.dat"));
////            ProcessBuilder builder2 = new ProcessBuilder("/bin/bash", "/root/anaconda3/surge_pre.sh");
////            builder2.directory(new File("/root/anaconda3"));
////            Process process2 = builder2.start();
////            process2.waitFor();
////            System.out.println(fileDel("/root/anaconda3/storm-surge/Stormtide_output.dat"));
////            ProcessBuilder builder3 = new ProcessBuilder("/bin/bash", "/root/anaconda3/storm_tide_pre.sh");
////            builder3.directory(new File("/root/anaconda3"));
////            Process process3 = builder3.start();
////            process3.waitFor();
////            bdms_calculatescheme_m.setState("3");
////        } catch (Exception e) {
////            System.out.println("执行命令时出错：" + e.getMessage());
////            bdms_calculatescheme_m.setState("2");
////        }
////
////        int res =bdms_calculatescheme_mService.insertBdmsCalculateschemeM(bdms_calculatescheme_m);
////        if (res>0){
////            return calId;
////        }
////        //当计算成功后 文件数据入库
////        //解析增水文件  然后入库 -p
////        List<Data> dataZsList= getValueModel("surge_output.dat");
////        Map<String, List<Data>> groupedByAge = dataZsList.stream()
////                .collect(Collectors.groupingBy(Data::getStcd));
////        // 打印分组结果
////        groupedByAge.forEach((stcd, dataList) -> {
////            //创建 -p 对象
////            BDMS_FBC_RESULT_P bdms_fbc_result_p = new BDMS_FBC_RESULT_P();
////            bdms_fbc_result_p.setCschemeid(calId);
////            if ("1919".equals(stcd)){
////                stcd ="70301400";
////            }else if ("1110".equals(stcd)){
////                stcd ="70703400";
////            }
////
////            bdms_fbc_result_p.setPtkey(stcd);
////            StringBuilder stringBuilder = new StringBuilder();
////            for (Data data1 : dataList){
////                stringBuilder.append(data1.getValue()+",");
////            }
////            bdms_fbc_result_p.setDttp(0);
////            System.out.println(bdms_fbc_result_p);
////        });
//
//
////        //状态
////        //执行完成返回数据
////        CalResults calResults = new CalResults();
////        calResults.setForecastTime(forecastTime);
////        IntForecastReslut intForecastReslut1919 = new IntForecastReslut();
////        intForecastReslut1919.setStationCode("70301400");
////        List<ValueModel> valueModels1919s = new ArrayList<>();
////
////        IntForecastReslut intForecastReslut1110 = new IntForecastReslut();
////        intForecastReslut1110.setStationCode("70703400");
////        List<ValueModel> valueModels1010s = new ArrayList<>();
////        ValueModel ValueModel1919tdz = new ValueModel();
////        ValueModel ValueModel1010tdz = new ValueModel();
////        List<Data> datatdz= getValueModel("tide_output.dat");
////        Map<String, List<Data>> groupedByAge = datatdz.stream()
////                .collect(Collectors.groupingBy(Data::getStcd));
////        // 打印分组结果
////        groupedByAge.forEach((stcd, dataList) -> {
////                if (Integer.parseInt(stcd)==70301400||Integer.parseInt(stcd)==1919){
////                    ValueModel1919tdz.setValues(dataList);
////                    Data maxData = dataList.stream().max(Comparator.comparingDouble(Data::getValue)).orElse(null);
////                    Data minData = dataList.stream().min(Comparator.comparingDouble(Data::getValue)).orElse(null);
////                    ValueModel1919tdz.setCalDataType("twc");
////                    ValueModel1919tdz.setValueName("天文潮");
////                    ValueModel1919tdz.setUnit("m");
////                    ValueModel1919tdz.setOrder(1);
////                    ValueModel1919tdz.setMaxValue(maxData.getValue());
////                    ValueModel1919tdz.setMaxTm(maxData.getTM());
////                    ValueModel1919tdz.setMinValue(minData.getValue());
////                    ValueModel1919tdz.setMinTm(minData.getTM());
////                    valueModels1919s.add(ValueModel1919tdz);
////
////                }else  if (Integer.parseInt(stcd)==70703400 ||Integer.parseInt(stcd)==1110){
////                    ValueModel1010tdz.setValues(dataList);
////                    Data maxData = dataList.stream().max(Comparator.comparingDouble(Data::getValue)).orElse(null);
////                    Data minData = dataList.stream().min(Comparator.comparingDouble(Data::getValue)).orElse(null);
////                    ValueModel1010tdz.setCalDataType("twc");
////                    ValueModel1010tdz.setValueName("天文潮");
////                    ValueModel1010tdz.setUnit("m");
////                    ValueModel1010tdz.setOrder(1);
////                    ValueModel1010tdz.setMaxValue(maxData.getValue());
////                    ValueModel1010tdz.setMaxTm(maxData.getTM());
////                    ValueModel1010tdz.setMinValue(minData.getValue());
////                    ValueModel1010tdz.setMinTm(minData.getTM());
////                    valueModels1010s.add(ValueModel1010tdz);
////
////                }
////
////
////        });
////      //  intForecastReslut.setStationCode((String)tdzMap.get("stcd"));
////        ValueModel ValueModel1919ftdz = new ValueModel();
////        ValueModel ValueModel1010ftdz = new ValueModel();
////        List<Data> dataftdz= getValueModel("Stormtide_output.dat");
////        Map<String, List<Data>> groupedByftdz = dataftdz.stream()
////                .collect(Collectors.groupingBy(Data::getStcd));
////        // 打印分组结果
////        groupedByftdz.forEach((stcd, dataList) -> {
////            if (Integer.parseInt(stcd)==70301400||Integer.parseInt(stcd)==1919){
////                ValueModel1919ftdz.setValues(dataList);
////                Data maxData = dataList.stream().max(Comparator.comparingDouble(Data::getValue)).orElse(null);
////                Data minData = dataList.stream().min(Comparator.comparingDouble(Data::getValue)).orElse(null);
////                ValueModel1919ftdz.setCalDataType("ftdz");
////                ValueModel1919ftdz.setValueName("预报潮位");
////                ValueModel1919ftdz.setUnit("m");
////                ValueModel1919ftdz.setOrder(2);
////                ValueModel1919ftdz.setMaxValue(maxData.getValue());
////                ValueModel1919ftdz.setMaxTm(maxData.getTM());
////                ValueModel1919ftdz.setMinValue(minData.getValue());
////                ValueModel1919ftdz.setMinTm(minData.getTM());
////                valueModels1919s.add(ValueModel1919ftdz);
////            }else  if (Integer.parseInt(stcd)==70703400 ||Integer.parseInt(stcd)==1110){
////                ValueModel1010ftdz.setValues(dataList);
////                Data maxData = dataList.stream().max(Comparator.comparingDouble(Data::getValue)).orElse(null);
////                Data minData = dataList.stream().min(Comparator.comparingDouble(Data::getValue)).orElse(null);
////                ValueModel1010ftdz.setCalDataType("ftdz");
////                ValueModel1010ftdz.setValueName("预报潮位");
////                ValueModel1010ftdz.setUnit("m");
////                ValueModel1010ftdz.setOrder(2);
////                ValueModel1010ftdz.setMaxValue(maxData.getValue());
////                ValueModel1010ftdz.setMaxTm(maxData.getTM());
////                ValueModel1010ftdz.setMinValue(minData.getValue());
////                ValueModel1010ftdz.setMinTm(minData.getTM());
////                valueModels1010s.add(ValueModel1010ftdz);
////
////            }
////        });
//////        Map<String, Object> zsMap = getValueModel("surge_output.dat", "zs");
////        ValueModel ValueModel1919ftdzs = new ValueModel();
////        ValueModel ValueModel1010ftdzs = new ValueModel();
////        List<Data> dataftdzs= getValueModel("surge_output.dat");
////        Map<String, List<Data>> groupedByftdzs = dataftdzs.stream()
////                .collect(Collectors.groupingBy(Data::getStcd));
////        // 打印分组结果
////        groupedByftdzs.forEach((stcd, dataList) -> {
////            if (Integer.parseInt(stcd)==70301400||Integer.parseInt(stcd)==1919){
////
////                Data maxData = dataList.stream().max(Comparator.comparingDouble(Data::getValue)).orElse(null);
////                Data minData = dataList.stream().min(Comparator.comparingDouble(Data::getValue)).orElse(null);
////                ValueModel1919ftdzs.setMaxValue(maxData.getValue());
////                ValueModel1919ftdzs.setMaxTm(maxData.getTM());
////                ValueModel1919ftdzs.setMinValue(minData.getValue());
////                ValueModel1919ftdzs.setMinTm(minData.getTM());
////                ValueModel1919ftdzs.setCalDataType("zs");
////                ValueModel1919ftdzs.setValueName("预报增水");
////                ValueModel1919ftdzs.setUnit("m");
////                ValueModel1919ftdzs.setOrder(3);
////                ValueModel1919ftdzs.setValues(dataList);
////                valueModels1919s.add(ValueModel1919ftdzs);
////            }else  if (Integer.parseInt(stcd)==70703400 ||Integer.parseInt(stcd)==1110){
////                Data maxData = dataList.stream().max(Comparator.comparingDouble(Data::getValue)).orElse(null);
////                Data minData = dataList.stream().min(Comparator.comparingDouble(Data::getValue)).orElse(null);
////                ValueModel1010ftdzs.setMaxValue(maxData.getValue());
////                ValueModel1010ftdzs.setMaxTm(maxData.getTM());
////                ValueModel1010ftdzs.setMinValue(minData.getValue());
////                ValueModel1010ftdzs.setMinTm(minData.getTM());
////                ValueModel1010ftdzs.setCalDataType("zs");
////                ValueModel1010ftdzs.setUnit("m");
////                ValueModel1010ftdzs.setValueName("预报增水");
////                ValueModel1010ftdzs.setOrder(3);
////                ValueModel1010ftdzs.setValues(dataList);
////                valueModels1010s.add(ValueModel1010ftdzs);
////            }
////        });
////        intForecastReslut1110.setValueModels(valueModels1010s);
////        intForecastResluts.add(intForecastReslut1110);
////        intForecastReslut1919.setValueModels(valueModels1919s);
////        intForecastResluts.add(intForecastReslut1919);
////        System.out.println("执行结束");
//        //return intForecastResluts;
//
//    }

}